J2EE HttpServlet. Controller's actions not working - java

I am following a tutorial book to develop a CRUD web application with J2EE and now it started using HttServlet. It might be that the book is not very new or that I don't really know how to do this.
I have my controller class, something like this:
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = null;
Action action = null;
if (request.getServletPath().equals("/Insert.do")) {
action = new InsertAction();
} else if (request.getServletPath().equals("/Delete.do")) {
action = new DeleteAction();
.....
} else {
action = new FilterShowAction();
}
dispatcher = request.getRequestDispatcher(action.execute(request, response));
dispatcher.forward(request, response);
}
}
The tutorial made me create a new different class for every different CRUD action, forms, and a couple more things.
Here's the Action class:
public abstract class Action {
public abstract String execute(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException;
}
But then when I type localhost:8080/myapp/Controller/SomeAction.do I get an Error 404. Only when I type localhost:8080/myapp/Controller I get something else: the last else block in the doGet method is executed; anyway, I get a NullPointerException.
I have no idea how to do this thing right, and the book doesn't give any more information. I couldn't find a solution anywhere else.
Also, I don't understad what is the .do extension. The book just comes up with it and makes you include it in your code without explaining what the heck it is. I didn't find any information in the Internet either.
Any help would be much appreciated.
EDIT
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Controller</servlet-name>
<display-name>Controller</display-name>
<servlet-class>mypackage.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>Controller</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.RuntimeException</exception-type>
<location>/Error.jsp</location>
</error-page>
</web-app>

Related

how to use guice correctly for dependency inject in java servlets?

sorry for the bad question title...
Disclaimer: Not much experience around web-apps, primarily used dropwizard.
So i have been trying to use guice in my java web-app
Initially without guice, servlets were serving the api correctly but after configuring servlet to be served from guice for below endpoint,
http://localhost:8080/myServlets/test
I am getting below error:
HTTP Status 404 – Not Found Type Status Report
Message The requested resource [/myServlets/test] is not available
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
Apache Tomcat/8.5.57
with below stacktrace:
16-Sep-2020 11:33:43.941 INFO [AsyncFileHandlerWriter-2008362258] org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load [com.google.inject.internal.util.LineNumbers$LineNumberReader]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [com.google.inject.internal.util.LineNumbers$LineNumberReader]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1378)
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1366)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1218)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:49)
at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:45)
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3529)
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2278)
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2155)
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2045)
at com.google.common.cache.LocalCache.get(LocalCache.java:3953)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3976)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4960)
at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4966)
at com.google.inject.internal.util.StackTraceElements.forMember(StackTraceElements.java:71)
at com.google.inject.internal.Messages.formatParameter(Messages.java:286)
at com.google.inject.internal.Messages.formatInjectionPoint(Messages.java:273)
at com.google.inject.internal.Messages.formatSource(Messages.java:229)
at com.google.inject.internal.Messages.formatSource(Messages.java:220)
at com.google.inject.internal.Messages.formatMessages(Messages.java:90)
at com.google.inject.ConfigurationException.getMessage(ConfigurationException.java:73)
at java.base/java.lang.Throwable.getLocalizedMessage(Throwable.java:396)
at java.base/java.lang.Throwable.toString(Throwable.java:485)
at java.base/java.lang.String.valueOf(String.java:2951)
at java.base/java.io.PrintWriter.println(PrintWriter.java:837)
at org.apache.juli.OneLineFormatter$IndentingPrintWriter.println(OneLineFormatter.java:298)
at java.base/java.lang.Throwable$WrappedPrintWriter.println(Throwable.java:768)
at java.base/java.lang.Throwable.printStackTrace(Throwable.java:659)
at java.base/java.lang.Throwable.printStackTrace(Throwable.java:725)
at org.apache.juli.OneLineFormatter.format(OneLineFormatter.java:171)
at org.apache.juli.FileHandler.publish(FileHandler.java:291)
at org.apache.juli.AsyncFileHandler.publishInternal(AsyncFileHandler.java:146)
at org.apache.juli.AsyncFileHandler$LogEntry.flush(AsyncFileHandler.java:185)
at org.apache.juli.AsyncFileHandler$LoggerThread.run(AsyncFileHandler.java:161)
Tried Guice Git but createInjector part stumps me as there is no main method.
Reference code is below, any help is appreciated!
CacheService
public interface CacheService {
public abstract String hello();
}
CacheServiceImpl
import com.google.inject.Provides;
public class CacheServiceImpl implements CacheService {
#Provides
public String hello() {
return "hello world";
}
}
CacheModule
import com.google.inject.AbstractModule;
public class CacheModule extends AbstractModule {
protected void configure() {
bind(CacheService.class).to(CacheServiceImpl.class);
}
}
MyGuiceServletConfig
public class MyGuiceServletConfig extends GuiceServletContextListener {
#Override
protected Injector getInjector() {
return Guice.createInjector(new ServletModule() {
#Override
protected void configureServlets() {
serve("/*").with(ResourceServlet.class);
bind(CacheModule.class);
}
});
}
}
ResourceServlet
#Slf4j
#Path("/")
#Singleton
public class ResourceServlet extends HttpServlet {
#Context
private ServletContext servletContext;
#Inject
public ResourceServlet(CacheService storageModule) throws JAXBException {
log.info("base {}", storageModule.hello());
}
#GET
#Path("/test")
#Produces({MediaType.APPLICATION_JSON})
public Product abc() {
log.info("servletContext {}", servletContext);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>myServlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Inject Guice -->
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.myorg.application.guice.MyGuiceServletConfig</listener-class>
</listener>
</web-app>

Google app engine No handlers matched this URL

i am going to call firebase Http request from a cron job i setup on google app engine.the cron job is deployed successfully but it did not trigger the firebase url as i think i am missing some setting in the web.xml file or in other files.
In the log viewer i see this type of info "No handlers matched this URL"
Any one have any idea.Any would be appreciated.
Following is my cron.xml setting
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/cron</url>
<target>beta</target>
<description>Keymitt cron job</description>
<schedule>every 1 minutes</schedule>
</cron>
</cronentries>
this is my web.xml setting
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloAppEngine</servlet-name>
<servlet-class>com.company.HelloAppEngine</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloAppEngine</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>KeymittCron</servlet-name>
<servlet-class>com.company.KeymittCron</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KeymittCron</servlet-name>
<url-pattern>/cron</url-pattern>
</servlet-mapping>
</web-app>
and this is my associated WebServlet
#WebServlet(name = "KeymittCron",value = "/cron")
public class KeymittCron extends HttpServlet {
private static final Logger _logger = Logger.getLogger(KeymittCron.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
URL url=new URL("httplink");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
int requestCode=connection.getResponseCode();
if(requestCode==200){
_logger.info("firebase link triggered successfully");
_logger.info("Executed cron job");
}
else{
_logger.info("Error while triggering firebase link");
}
connection.disconnect();
resp.setStatus(200);
resp.getWriter().println("Done");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
doGet(req,resp);
}
}
And this is my Logger info
My answer here may be relevant - Google Cloud App Engine cron job - not calling the service
Basically, you may need this in your appengine-web.xml:
<service>beta</service>
The <target> you specify in your cron.xml must match the <service> you define in your appengine-web.xml

filter that forwards to index page

I want to make a filter that would forward to /WEB-INF/index.html request to application that looks like this
http://localhost:8080/basic-application-web
Here is my filter
public class RootFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (req.getRequestURI().equals("/basic%2Dapplication%2Dweb/")) {
req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);
}
chain.doFilter(request, response);
}
#Override
public void destroy() {}
}
My web.xml looks like this
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://java.sun.com/xml/ns/javaee'
xmlns:web='http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd'
xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaeeweb-app_2_5.xsd'
id='basic_web' version='2.5'>
<display-name>Basic web application</display-name>
<servlet>
<servlet-name>serviceServlet</servlet-name>
<servlet-class>com.pack.ServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>serviceServlet</servlet-name>
<url-pattern>/messaging</url-pattern>
</servlet-mapping>
<filter>
<filter-name>rootFilter</filter-name>
<filter-class>com.pack.RootFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>rootFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
However from time to time I get some weird behaviour where tomcat (I use it to deploy the war) is unable to find basic-application-web when I try to access directly using URL.
Though through tomcat manager it works fine. What is the problem? Maybe due to missing root servlet?
I moved index.html outside WEB-INF so basically the layout started to look like this
webapp
WEB-INF\web.xml
index.html
And adjusted filter to forward to /index.html instead of WEB-INF/index.html
req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);
It has helped.

404 in Jersey/Struts application

I am trying to use Jersey to provide a simple web service for my struts application.
When I call the client action I get the following error
com.sun.jersey.api.client.UniformInterfaceException
Message: GET http://localhost:8080/shumer/rest/employee/get returned a response status of 404
servlet declaration in web.xml
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>spring.autowire</param-name>
<param-value>byName</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Server resource
#Path("employee")
public class EmployeeResource {
#Autowired
EmpDao empDao;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Employee> get(#QueryParam("empCode") String empCode) throws Exception {
EmpCriteria criteria = new EmpCriteria();
criteria.setEmpCode(empCode);
return empDao.searchByCondition(criteria);
}
}
Client action
public class EmployeeClientTestAction extends Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/shumer/rest/employee/get");
String employees= resource.accept(MediaType.APPLICATION_JSON)
.get(String.class);
System.out.println(employees);
request.setAttribute("employees", employees);
return mapping.findForward("successful");
}
}
I have tried this with and without the /get and the end of the resource url, and with and without a leading / in the EmployeeResource #Path annotation. My guess is that there is somewhere I have to declare where my resources are lcoated at in order for the Jersey servlet to handle them, but I can't figure it out. A point in the right direction would be much appreciated.
EDIT
I have added the following init-param to the servlet element and it is still not working (this package is where my resource class is)
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>shumer.rest.resource</param-value>
</init-param>
in get method write #Path("/get")

Server not responding for some request

I am having problem in some request access, in my web application. I am not able to figure out the issue.
In my we application servlet mapping configuration is like this..
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and the spring configuration for dispatcher servlet is like this.
In WebApplicationInitializerConfig
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
ServletRegistration.Dynamic dispatcher;
dispatcher = servletContext.addServlet("api/", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
String apiMappingPath = /api/*;
dispatcher.addMapping(apiMappingPath);
When I make some API request, the call goes to the method and method sout also print in server log.But no response comes out.
For information I am deploying the application on glassfish server.
I am not able to get the issue reason also. If any one knows then help me out.
Method code:
#RequestMapping(value = "/email", method = RequestMethod.POST)
public Map passwordResetMail(#RequestBody(required = false) String email, HttpServletRequest request, HttpServletResponse response) {
system.out.println("email"+email);
Map map = new HashMap();
map.put("email",email);
return map;
}

Categories

Resources