I'm prototyping an e-commerce web application using Servlets and JSPs, so in order to make regular queries to get the status of a transaction (paid/not paid) from another server without stopping the web application, I'm trying to learn how to use asynchronous Servlets. After some reading and failed attempts of making examples of AsyncServlets found on the web, I've found maybe the simplest one on this video. Even so, it's giving me a headache. It throws an IllegalStateException, even if all the things seem to be in order, since it's a very simple application with no external libraries. I'm using NetBeans IDE 8.2, Java EE 7 Web and Tomcat 8.0.27.
This is the code:
package com.za.tutorial.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = {"/ProgressAsyncServlet"}, asyncSupported=true)
public class ProgressAsyncServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<html><head><title>Progress Async Servlet</title></head><body>");
printWriter.println("entering doGet() ==> thread name: " + Thread.currentThread().getName() + "<br>");
printWriter.println("<progress id='progress' max='100'></progress>");
AsyncContext asyncContext = request.startAsync();
asyncContext.start(() -> {
printWriter.println("thread name within asyncContext.start((): " + Thread.currentThread().getName() + "<br>");
int i = 0;
while (i <= 100) {
printWriter.println("<script>document.getElementById('progress').value=\"" + i++ + "\";</script>");
printWriter.flush();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
printWriter.println("<script>document.getElementById('progress').style.display='none';</script>");
printWriter.println("[time consuming generated and returned result]<br>");
printWriter.println("exiting doGet() ==> thread name: " + Thread.currentThread().getName() + "<br>");
printWriter.println("</body></html>");
asyncContext.complete();
});
}
}
Running the file containing the example of the synchronous ProgressServlet is ok, as expected. Though, after running the ProgressAsyncServlet file, which contains almost the same code (but with asynchronous methods), I get the following log:
04-Mar-2021 08:50:03.188 SEVERE [http-nio-8084-exec-23] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.za.tutorial.servlet.ProgressAsyncServlet] in context with path [/AsyncServletPrj01] threw exception
java.lang.IllegalStateException: A filter or servlet of the current chain does not support asynchronous operations.
at org.apache.catalina.connector.Request.startAsync(Request.java:1612)
at org.apache.catalina.connector.Request.startAsync(Request.java:1605)
at org.apache.catalina.connector.RequestFacade.startAsync(RequestFacade.java:1030)
at javax.servlet.ServletRequestWrapper.startAsync(ServletRequestWrapper.java:373)
at com.za.tutorial.servlet.ProgressAsyncServlet.doGet(ProgressAsyncServlet.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
It's driving me crazy. How can such a simple code work this wrong?
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Create a servlet that uses cookies to store the number how many times user has visited?-That's the question im trying to solve
this is my html
<html>
<head>
</head>
<body>
<form action="NewServlet">
<input type="text" name="text1">
<input type="submit"/>
</form>
</body>
</html>
this is NewServlet.java
public class NewServlet extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
Cookie[] cook=req.getCookies();
String s=req.getParameter("text1");
int a=0;
if(cook.length>0)
{
for(Cookie cookie :cook)
{
if(cookie.getName().equals(s))
{
int b=Integer.parseInt(cookie.getValue());
b=b+1;
cookie.setValue(String.valueOf(b));
a++;
}
}
}
if(a>0)
{
res.sendRedirect("NewServlet1");
}
else
{
Cookie cok=new Cookie(s,"1");
res.addCookie(cok);
req.setAttribute("user", s);
RequestDispatcher r=req.getRequestDispatcher("NewServlet1");
r.forward(req,res);
}
}
}
and this is NewServlet1.java
public class NewServlet1 extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
Cookie[] cookie=req.getCookies();
String s=String.valueOf(req.getAttribute("user"));
for(Cookie cok:cookie)
{
if(cok.getName().equals(s))
{
int a=Integer.parseInt(cok.getValue());
res.getWriter().println("number of times visited"+a);
}
}
}
}
what i am doing is checking if cookie exist or not and if no then creating the cookie on NewServlet.java .But i am getting a Null-Pointer Exception (Error 500)
on clicking the submit button
stacktrace
at First.NewServlet.service(NewServlet.java:28)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Change if(cook.length>0) to if(cook !=null && cook.length > 0). This way if cook is null then it will not check the .length and hence avoid the NPE
I have some code for download file from web server.
Everything works alright, but in console I have this exception:
июн 26, 2015 2:08:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/TestTask] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:462)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:109)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:57)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:909)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:576)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Why and what it can be? And how i can fix this problem? I try find answer in the google, but I failed.
The code:
package actions;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import org.apache.log4j.Logger;
import org.apache.struts.chain.contexts.ServletActionContext;
import service.CsvCreator;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadCsvAction extends ActionSupport {
private static final long serialVersionUID = -4714537109287679996L;
private CsvCreator CSVcreator;
private static final Logger logger = Logger.getLogger(DownloadCsvAction.class);
public CsvCreator getCSVcreator() {
return CSVcreator;
}
public void setCSVcreator(CsvCreator cSVcreator) {
CSVcreator = cSVcreator;
}
#Override
public String execute() {
HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment; filename=\"phone_records.csv\"");
response.setContentType("text/csv");
ServletOutputStream out;
try {
out = response.getOutputStream();
String tableHeader = "Caller, Event, Reciever, Timestamp\n";
out.write(tableHeader.getBytes("UTF-8"));
out.write(CSVcreator.getAllRecordsInString().getBytes("UTF-8"));
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return SUCCESS;
}
}
And my struts.xml:
<action name="DownloadCsvAction" class="DownloadCsvAction">
<result name="success" type="dispatcher"/>
</action>
Why and what it can be?
Because response is already committed. You have closed response before it's used by the Struts2.
And how I can fix this problem?
When your action execution ends, return Action.NONE result code. This code tells the invoker to not execute any result because response might be already committed.
You can also rewrite the action implementation to use stream result type. In this way you have not to do with the response and let Struts2 do the rest. Example of using stream result is here.
This question already has answers here:
Where has org.apache.batik.dom.svg.SVGDOMImplementation gone?
(4 answers)
Closed 1 year ago.
I have a servlet where i´m trying to create a pdf out of a string containing svg code. Therefore i have this code:
public class Conversion extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String svgString = req.getParameter("svg");
StringReader svg = new StringReader(svgString);
File pdf = new File("/tmp/chart.pdf");
Transcoder transcoder = new PDFTranscoder();
TranscoderInput transcoderInput = new TranscoderInput(svg);
TranscoderOutput transcoderOutput = new TranscoderOutput(new FileOutputStream(pdf));
try {
transcoder.transcode(transcoderInput, transcoderOutput);
} catch (TranscoderException e) {
e.printStackTrace();
}
resp.setContentType("application/pdf");
InputStream in = new FileInputStream(pdf);
ServletOutputStream out = resp.getOutputStream();
byte[] buffer = new byte[4096];
while(in.read(buffer, 0, 4096) != -1){
out.write(buffer, 0, 4096);
}
in.close();
out.flush();
out.close();
}
}
When executing i get this error:
java.lang.ClassNotFoundException: org.apache.batik.dom.svg.SVGDOMImplementation
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1332)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
at org.apache.fop.svg.AbstractFOPTranscoder.<init>(AbstractFOPTranscoder.java:107)
at org.apache.fop.svg.PDFTranscoder.<init>(PDFTranscoder.java:84)
at com.Webmap_read.Conversion.doGet(Conversion.java:38)
at com.Webmap_read.Conversion.doPost(Conversion.java:68)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
When i check my Build Path, it seems like all the JARs that are contained in the Batik 1.8 archive file downloaded from: http://apache.lauf-forum.at/xmlgraphics/batik/binaries/. But the class SVGDOMImplementation is not there. How can i import all the necessary JARs/classes and why aren´t they contained in the standard zip? It´s driving me crazy right now... Or is there maybe an easier way to convert an SVG to PDF?
Take a look at http://www.findjar.com/class/org/apache/batik/dom/svg/SVGDOMImplementation.html an check if any of listed jars are in application classpath.
I suggest you to download Batik from https://xmlgraphics.apache.org/batik/download.html (official website)
Make sure all the necessary/related jar files are present when you compile your class. Simply reference any and all related folders by using javac -cp "[path to first folder with related jars]\*;[path to second folder with related jars]\*;[path to last folder with related jars]\*" yourclass.java .
This question already has an answer here:
java.lang.IllegalStateException: Cannot forward after response has been committed in servlet [duplicate]
(1 answer)
Closed 7 years ago.
I am trying to learn abt servlets.
I am getting a IllegalStateException when i call forward(). The error occurs in the LoginBean.do if block at the point where i call forward.
process(request,response);
}
private void process(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String uri = request.getRequestURI();
RequestDispatcher rd = null;
CAppModel model = new CAppModel();
System.out.println("Inside process ()");
try{
if(uri.contains("/Login"))
{
System.out.println("Inside Login.do");
rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request,response);
}
if(uri.contains("/Register.do"))
{
System.out.println("inside Register.do");
}
if(uri.contains("/LoginBean.do"))
{
System.out.println("Inside LoginBean.do");
LoginBean lb = (LoginBean)request.getAttribute("login");
System.out.println("toString(): "+lb.toString());
String result = model.authenticate(lb);
System.out.println("CS: result of auth "+result);
if(result.equals("Success"))
{
System.out.println("Inside if Success of loginbean");
HttpSession session = request.getSession(true);
session.setAttribute("user", lb.getEmail());
rd = request.getRequestDispatcher("Menu.jsp");
rd.forward(request, response);
}
else
{
System.out.println("failed auth "+result);
request.setAttribute("errorMsg", result);
rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request,response);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
process(request,response);
}
}
I am getting the following error
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:328)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at com.aditya.CApp.ControllerServlet.process(ControllerServlet.java:69)
at com.aditya.CApp.ControllerServlet.doGet(ControllerServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:741)
at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:711)
at org.apache.jsp.LoginInt_jsp._jspService(LoginInt_jsp.java:104)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
A request containing /LoginBean.do will trigger 2 if blocks causing 2 forwards to be invoked causing the error after the 2nd forward. While you could re-arrange the the if statements as
if (uri.contains("/LoginBean.do")) {
...
else if (uri.contains("/LoginBean")) {
...
Generally its simpler to use an individual servlet per if block functionality.
you must return; after a forward. otherwise the following code would executed also... in your case the conditions containing /Login and /LoginBean.do
The full error: java.lang.NoClassDefFoundError: Could not initialize class lt.maze.dao.DAO
The class DAO is used from my LoginServlet. It is compiled and deployed, I checked WEB-INF/classes. DAO.class exists.
Why is isn't it loaded? Am I suppose to add them to my classpath manually? (I have the manifest file to load my properties file).
LoginServlet.java:
#WebServlet(name = "LoginServlet", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
#Override
public void init() throws ServletException
{
System.out.println("System. out. Its online.");
getServletContext().log("LoginServlet initialised");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().log("Http request. Request URI: " + request.getRequestURI());
System.out.println("Http request. Request URI: " + request.getRequestURI());
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username == null || password == null) {
response.sendError(401);
} else {
UserDAO userDAO = DAO.getUserDAO();
User user = userDAO.find(username, password);
if(user == null) {
response.sendError(401, "Invalid username or password");
} else {
String sessionToken = SessionTokens.getSessionToken();
response.addCookie(new Cookie("session-token", sessionToken));
getServletContext().log("Valid connection. token:"+sessionToken);
}
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().log("Request received via GET.");
System.out.println("Requeswt received via GET");
}
}
Full stacktrace:
18-May-2015 14:49:35.133 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [LoginServlet] in context with path [/ChatApp] threw exception [Servlet execution threw an exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class lt.maze.dao.DAO
at lt.maze.LoginServlet.doPost(LoginServlet.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
If an exception is propagating out of the constructor of the class or a static initializer, then you also get java.lang.NoClassDefFoundError: Could not initialize class ... .