I am creating a login page where Engineer can login through their username started with "engg".
The problem is in the login page when I am giving the right input with right password it gives "Illegal State Exception".In wrong inputs it works fine.Like When i am giving "engg140" present in my oracle table it is giving the exception.the code is:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.java2d.pipe.GeneralCompositePipe;
import accessdb.Dao;
import accessdb.Getset;
public class AdminLogIn extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #return
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
String username=request.getParameter("username");
String password=request.getParameter("password");
Getset g=new Getset();
Dao dao=new Dao();
if(username.equals("") || password.equals(""))
{
response.sendRedirect("login.jsp");
}
else{
String newuname=username.substring(0,4);
// System.out.println(""+username);
if(newuname.equals("engg"))
{
ResultSet rs=dao.EnggLogInUseridCheck(g);
System.out.println(""+newuname);
while(rs.next())
{
String uname=rs.getString("uname");
System.out.println(""+uname);
if(uname.equals(username))
{
g.setuname(username);
System.out.println(""+username);
System.out.println(""+uname);
ResultSet rs1=dao.EnggLogInPasswordCheck(g);
while(rs1.next())
{
String password1=rs1.getString("password");
if(password1.equals(password))
{ System.out.println(""+password1);
System.out.println(""+password);
response.sendRedirect("engghome.jsp");
break;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
}
response.sendRedirect("login.jsp");
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The console output for a right input is as follows:
03:31:26,265 INFO [STDOUT] engg
03:31:26,265 INFO [STDOUT] engg172
03:31:26,265 INFO [STDOUT] engg140
03:31:26,265 INFO [STDOUT] engg140
03:31:26,265 INFO [STDOUT] engg140
03:31:26,281 INFO [STDOUT] 365125
03:31:26,281 INFO [STDOUT] 365125
03:31:26,281 INFO [STDOUT] engg141
03:31:26,281 ERROR [[AdminLogIn]] Servlet.service() for
servlet
AdminLogIn threw exception
java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435)
at AdminLogIn.doGet(AdminLogIn.java:80)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
You did not included the "caused by" sections of the stack trace, which are the most important part (actually, the WHOLE stack trace is important).
An, IllegalStateException on a sendRedirect() has to do with the HTTP protocol, and occurs when the response to the client has already been committed. At this point it is not possible to send a redirect any more as the HTTP headers have been sent (or at least queued to be sent) and cannot be changed. Somewhere in your code, in a method you haven't shown, you have written something to the output stream and caused the response to be committed.
This has nothing to do with the database.
I think the response is already committed which is not allowing you to do redirect.
Look here for more information:
Cause Of Response already committed
IllegalStateException while sendRedirect
Related
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?
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.
Exception when writing the response back using jackson. Unable to find any solutions on the net. I am not sure what is the cause of error. Tried flushing the response but still the same error
import com.In10s.DBProperties.OracleDBConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
public class GetTable extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
try {
JSONArray data = new JSONArray();
Connection con = OracleDBConnection.getConnection();
String query = "Select * from CREDIT_CARD_TRANSACTIONS";
Statement st = con.createStatement();
ResultSet rSet = st.executeQuery(query);
List<Map<String, Object>> result = new ArrayList<>();// JDK7++
while (rSet.next()) {
Map<String, Object> row = new HashMap<>();
row.put("CARD_NUMBER", rSet.getString("CARD_NUMBER"));
row.put("FIRST_NAME", rSet.getString("FIRST_NAME"));
row.put("OPENING_BALANCE", rSet.getString("OPENING_BALANCE"));
row.put("WITHDRAWAL", rSet.getString("WITHDRAWAL"));
row.put("DEPOSIT", rSet.getString("DEPOSIT"));
row.put("CLOSING_BAL", rSet.getString("CLOSING_BAL"));
row.put("TXDATE", rSet.getString("TXDATE"));
row.put("USAGE_TYPE", rSet.getString("USAGE_TYPE"));
result.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
try {
response.getWriter().write(mapper.writeValueAsString(response));
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Here is stack trace:
com.fasterxml.jackson.databind.JsonMappingException: getWriter() has already been called for this response (through reference chain: org.apache.catalina.connector.ResponseFacade["outputStream"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:190)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:671)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3383)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2777)
at com.In10s.getTable.GetTable.doGet(GetTable.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:644)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:196)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:536)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663)
... 28 more
You're trying to transform the HttpServletResponse into JSON, and send it to the HttpServletResponse. You want to transform the result list to JSON instead:
response.getWriter().write(mapper.writeValueAsString(result));
I want to catch and ignore the following tomcat ClientAbortException.
As it is unnecessary to pay any attention on this for my program.
Any idea how and where I can catch this exception?
Below is the Exception:
14:46:43.920 [ajp-bio-8029-exec-538] ERROR com.sok.runway.URLFilter - Exception in URLFilter
org.apache.catalina.connector.ClientAbortException: null
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:388) ~[catalina.jar:7.0.26]
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:462) ~[tomcat-coyote.jar:7.0.26]
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:366) ~[tomcat-coyote.jar:7.0.26]
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:413) ~[catalina.jar:7.0.26]
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:401) ~[catalina.jar:7.0.26]
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:91) ~[catalina.jar:7.0.26]
at org.apache.catalina.servlets.DefaultServlet.copyRange(DefaultServlet.java:2031) ~[catalina.jar:7.0.26]
at org.apache.catalina.servlets.DefaultServlet.copy(DefaultServlet.java:1870) ~[catalina.jar:7.0.26]
at org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:958) ~[catalina.jar:7.0.26]
at org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:411) ~[catalina.jar:7.0.26]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) ~[servlet-api.jar:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) ~[servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.26]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.26]
at com.sok.runway.URLFilter.doFilter(URLFilter.java:130) ~[runway-dev.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.26]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.26]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224) [catalina.jar:7.0.26]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) [catalina.jar:7.0.26]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [catalina.jar:7.0.26]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) [catalina.jar:7.0.26]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) [catalina.jar:7.0.26]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) [catalina.jar:7.0.26]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.26]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) [catalina.jar:7.0.26]
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200) [tomcat-coyote.jar:7.0.26]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579) [tomcat-coyote.jar:7.0.26]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) [tomcat-coyote.jar:7.0.26]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [na:1.7.0_03]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [na:1.7.0_03]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03]
Caused by: java.net.SocketException: Connection reset
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113) ~[na:1.7.0_03]
at java.net.SocketOutputStream.write(SocketOutputStream.java:153) ~[na:1.7.0_03]
at org.apache.coyote.ajp.AjpProcessor.output(AjpProcessor.java:295) [tomcat-coyote.jar:7.0.26]
at org.apache.coyote.ajp.AbstractAjpProcessor$SocketOutputBuffer.doWrite(AbstractAjpProcessor.java:1082) ~[tomcat-coyote.jar:7.0.26]
at org.apache.coyote.Response.doWrite(Response.java:533) ~[tomcat-coyote.jar:7.0.26]
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:383) ~[catalina.jar:7.0.26]
since you probably don't want a dependency to Catalina, you can ignore the Exception like this (I'm assuming the ClientAbortException is the cause):
String simpleName = e.getCause().getClass().getSimpleName();
if (simpleName.equals("ClientAbortException")) {
// ignore
} else {
// do whatever you do
}
In Spring 4, you would put this in a class annotated with #ControllerAdvice. The trick is to only suppress ClientAbortException while allowing every other IOException to be handled as errors or logged, without introducing a compile/runtime dependency on your container API:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
//import org.apache.catalina.connector.ClientAbortException; // We don't want this dependency.
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
#ControllerAdvice
public final class ErrorController
{
#ExceptionHandler(NoHandlerFoundException.class)
public String handleNoHandlerFoundException(final NoHandlerFoundException ex)
{
return "notFoundPage";
}
#ExceptionHandler(IOException.class)
public String handleAbortedConnection(final IOException ex)
{
// avoids compile/runtime dependency by using class name
if (ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException"))
{
return null;
}
// log and return error page for any other IOExceptions
if (LOGGER.isLoggable(Level.WARNING))
{
LOGGER.log(Level.WARNING, "IO Error", ex);
}
return "errorPage";
}
#ExceptionHandler(Exception.class)
public String handleException(final Exception ex)
{
if (LOGGER.isLoggable(Level.SEVERE))
{
LOGGER.log(Level.SEVERE, "Server Error", ex);
}
return "errorPage";
}
}
Thanks to this answer for providing the missing piece where we return null for the view name to avoid throwing a SocketException on the closed OutputStream.
ClientAbortException extends IOException. You can try the code below to catch the exception:
try {
// codes
out.write("xyz"); // throws IOException
} catch (org.apache.catalina.connector.ClientAbortException ca) {
System.out.println("ClientAbortException caught");
} catch (IOException ioe) {
System.out.println("i/o exception raised. abrorting.");
}
i am developing a project KNOWLEDGE based community sharing system.
in which users can login and share their resources to other Users....
I'm getting a problem in uploading a file to mysql database....
PS..my Instructor strictly Says to use MVC architecture So, i have to use the same..
So i have created only one Servlet named Controller.java.
here i will redirect to other java programs for calculations...
Here is the code for Controller.java
package com.kbcss.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {super();}
#SuppressWarnings("rawtypes")
private Map commands = new HashMap();
#SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException{
super.init();
System.out.println("i am in init");
this.commands.put("login", new LoginCommand());
this.commands.put("user", new UserCommand());
this.commands.put("resource", new ResourceCommand());
System.out.println("i am about to exit init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in doget");
processCommand(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in dopost");
processCommand(request, response);
}
private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in processCommand");
String formAction = request.getParameter("form_action");
System.out.println("i am in processCommand state 2");
Commands command = (Commands) commands.get(formAction);
command.execute(request, response);
System.out.println("i am about to exit processCommand");
}
}
and here is the code for saving the resources to MY database table.... Named ResourceCommand .java
package com.kbcss.command;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;
import com.oreilly.servlet.MultipartRequest;
public class ResourceCommand extends HttpServlet implements Commands{
private static final long serialVersionUID = 1L;
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//
// JNDI to connect to database
//
Connection conn = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
conn = ds.getConnection();
//
// Save file(s) temporarily to filesystem
//
MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
Enumeration files = multi.getFileNames();
String filename = "";
File f = null;
while(files.hasMoreElements()) {
String name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
f = multi.getFile(name);
}
//
// Insert file into database
//
InputStream is = new FileInputStream(f);
String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
PreparedStatement stmt = conn.prepareStatement(sql);
// Set some Title
stmt.setString(1, "some thing");
// Set some category
stmt.setString(2, ".net");
// Set some user
stmt.setString(3, "sri");
// Set Filename
stmt.setString(4, f.getName());
// Set the data
stmt.setBinaryStream(5, is, (int) f.length());
// Set Likes
stmt.setInt(6, 2);
stmt.executeUpdate();
is.close();
//
// Release connection
//
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
} catch(Exception e) {
System.out.println(e);
}
}
}
And here is the jSP file where i will upload from....
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>UPLOAD FILE page</title></head>
<body>
<form method="post" action="Controller" enctype="multipart/form-data">
<input type="hidden" name="form_action" value="resource" />
<b>File to upload to database:</b>
<input type="file" name="attachment" size="36">
<input type="submit" value="Upload">
</form>
</body></html>
And this is the error i'm getting :(
INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
at com.kbcss.controller.Controller.processCommand(Controller.java:69)
at com.kbcss.controller.Controller.doPost(Controller.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and by the way..i have created a Command.java interface here it is.
package com.kbcss.command;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public interface Commands {
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ
i'm stuck for a day and Half and have no clue what i'm doing...
This is what happens if u ask an electrical engineering student to do a Java Project !!!!
GREAT GREAT thanks from My side.....
Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.
Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).
One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:
private Map<String,Command> commands = new HashMap<String,Command>();
After you do that, you shouldn't have to suppress the warning on the Map.