Trying to call a servlet when loading a jsp - java

I am building a simple Train booking system, now i am trying to call a servlet once i open a jsp to select data from the database then return back to the same servlet, but i keep getting errors.
this is my trip.jsp
<body>
<% if ((request.getAttribute("trips") == null)) {
%>
<jsp:include page="/trips" flush="true" />
<% } %>
<table>
<tr>
<th>Trip Number</th>
<th>Train Number</th>
<th>Source</th>
<th>Destination</th>
<th>Departure Time</th>
<th>Arrival Time</th>
<th>Date</th>
<th>Reserved Seats</th>
<th>Price</th>
</tr>
<%
//ArrayList list = new ArrayList();
List trip = new ArrayList();
Iterator viewTrip;
if(request.getAttribute("trips")!=null && request.getAttribute("trips")!=""){
List allTrips = (ArrayList)request.getAttribute("trips");
Iterator itr = allTrips.iterator();
while(itr.hasNext()){
trip = (ArrayList)itr.next();
viewTrip = trip.iterator();
%>
<tr>
<%
while(viewTrip.hasNext()){
%>
<td>
<%=viewTrip.next()%>
</td>
<%
}
%>
</tr>
<%
}
}
%>
</table>
</body>
and this is my servlet. trips.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection con = DB.getActiveConnection();
Statement stmt = con.createStatement();
ResultSet rs = null;
ArrayList trip = new ArrayList();
ArrayList data = null;
try {
String query = "select * from trips";
rs = stmt.executeQuery(query);
while(rs.next()){
data = new ArrayList();
data.add(rs.getString(9)); // trip number
data.add(rs.getInt(1)); // train number
data.add(rs.getString(2)); // source
data.add(rs.getString(3)); // destination
data.add(rs.getTime(4)); //departure time
data.add(rs.getTime(5));// arrival time
data.add(rs.getDate(6));// date
data.add(rs.getInt(7));// reserved seats
data.add(rs.getDouble(8));//price
trip.add(data);
}
request.setAttribute("trips", trip);
con.close();
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/updateTrip.jsp");
requestDispatcher.include(request, response);
//out.close();
//return;
}
catch (Exception e) {
e.printStackTrace();
}
}
and this is the error i get
25-Dec-2016 15:47:01.822 SEVERE [http-nio-8084-exec-4]
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/Train] threw exception [java.lang.IllegalStateException: Exception occurred when flushing data] with root cause
java.io.IOException: Stream closed
at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:200)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:105)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:184)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.updateTrip_jsp._jspService(updateTrip_jsp.java:199)
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.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: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)

You are using try with resources, which automatically closes the stream while exiting the try block.
try (PrintWriter out = response.getWriter()) {
....
}
trip.jsp passes request and response objects to the servlet trips.java, where you get the PrintWriter of the response (and for some reason, not using it anywhere) in a try with resource, which will close the underlying stream at the end of the try block. Now, when your include is finished and control comes back to the trip.jsp and try to write the jsp content, it'll fail as the stream is already closed.
Just change your code as:
PrintWriter out = response.getWriter();
try {
....
} catch (IOException e) {
....
}
or if you don't want to handle the exception here, just remove the try altogether.

Related

Servet - Why am i getting null pointer exception? [duplicate]

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

Cannot forward after response has been committed in servlet filter [duplicate]

This question already has answers here:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
(9 answers)
Closed 6 years ago.
I am trying to catch exception in servlet filter and the forward to an error page.
But when I catched the exception in filter and using request.getRequestDispatcher("/error.html").forward(request, response); to forward to the error page it is throwing me the error saying Cannot forward after response has been committed.
Code:
public class TestFilter implements Filter {
private String encoding = null;
public void destroy() {
encoding = null;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
try {
chain.doFilter(request, response);
double value = 1/0;// to make an exception
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.getRequestDispatcher("/error.html").forward(request, response);
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Stacktrace:
java.lang.ArithmeticException: / by zero
at com.baoming.filter.TestFilter.doFilter(TestFilter.java:27)
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:501)
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:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
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)
Jan 26, 2017 3:01:54 下午 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springmvc] in context with path [/Monitor] threw exception
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.baoming.filter.TestFilter.doFilter(TestFilter.java:31)
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:501)
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:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
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)
I made the ArithmeticException to specify the problem. If I move the code double value = 1/0; before chain.doFilter(request, response);,it will not throw Cannot forward after response has been committed exception.
I don't know how to fix the problem. If an exception occurs after chain.doFilter(request, response);, how can I catch it and forward to another page?
just a guess: you need to swap chain.doFilter(request, response); and double value = 1/0; because at the moment you rise the exception after your servlet has done the work:
try {
double value = 1/0;// to make an exception
chain.doFilter(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.getRequestDispatcher("/error.html").forward(request, response);
}

"getOutputStream()" has already been called for this response

i'm working on a project with Spring, i have this problem, i google the error message and i did find a solutions even all SO posts about this same problem
java.lang.IllegalStateException: "getOutputStream()" has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:578)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:115)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:108)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:175)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.WEB_002dINF.Pages.generate_jsp._jspService(generate_jsp.java:209)
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.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:230)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
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.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:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)
this is my controller :
#RequestMapping(method = RequestMethod.GET, value = "/GenerateM")
public String genererGet(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
// Some code ...
OutputStream out;
try {
response.setContentType("rtf");
String filename = name + ".out.rtf";
response.setHeader("Content-Disposition", "attachment; filename = " + filename);
out = response.getOutputStream();
FileInputStream in = new FileInputStream(new File(rtf.getRtfOutput()));
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
out.close();
} catch (IOException a) {
a.printStackTrace();
}
return "generate";
}
i saw many SO posts like : THIS and THIS and THIS but no solution for me
can some one help ?
You start by writing a response by yourself, and then return the name of the view, and thus telling Spring that it should generate an HTML page using the generate.jsp.
Make your method return void instead of a String. An HTTP response can have only one body: either it's a file attachment, or an HTML page, but not both.
#JB Nizet Thank's for help. In my case, I retured ModelAndView ojbect when download failing to forward error page:
#RequestMapping(value = { "/downloadfile.action" }, method = RequestMethod.POST)
public ModelAndView downloadFile(HttpServletRequest req, HttpServletResponse res, Model model)
{
catch (Excetion e) {
return errorPage
}
}
I change that to return null

Getting an IllegalStateException when i call forward() [duplicate]

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

Tomcat JSP error 500

I have experienced this strange error, and now I will explain when this happens:
basically what I have to do is having an HTML form (or JSP, doesn't really matter) with a simple textfield and two buttons, one for submitting to the .jsp page and the other one is just to reset the textfield.
Everything is working fine, except when I try to write in the textfield something with spaces (example: "abc 123").
If I simply write "abc123" it doesn't give any error 500 though.
I hope some of you can help me, here are the sources:
<html>
<head>`<html>
<head>
<meta charset="ISO-8859-1">
<title>HTML Form</title>
</head>
<body>
<form name = "intoll" method = "post" action = "send.jsp">
Insert text: <input type = "text" name = "food" id = "food">
<br/>
<input type = "submit" name = "send" value = "Send">
<input type = "reset" name = "Reset">
</form>
</body>
send.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.athirat.intolleranze.foods.*" %>
<%
String food = request.getParameter("food").trim();
if (food != null && food != "") {
food = food.toLowerCase();
out.print(food);
NetMaster.init(food);
}
%>
<!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">
</head>
<body>
<%
try {
out.print(NetMaster.showContent());
} catch (Exception e) {
throw new Exception("String error");
}
%>
</body>
</html>
Thanks for helping me.
EDIT:
Stacktrace
giu 16, 2015 3:06:12 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jsp] in context with path [/intoll] threw exception [An exception occurred processing JSP page /send.jsp at line 22
19: try {
20: out.print(NetMaster.showContent());
21: } catch (Exception e) {
22: throw new Exception("String error");
23: }
24: %>
25: </body>
Stacktrace:] with root cause
java.lang.Exception: Errore nella stringa
at org.apache.jsp.send_jsp._jspService(send_jsp.java:113)
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:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)
giu 16, 2015 3:23:56 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jsp] in context with path [/intoll] threw exception [An exception occurred processing JSP page /send.jsp at line 22
19: try {
20: out.print(NetMaster.showContent());
21: } catch (Exception e) {
22: throw new Exception("String error");
23: }
24: %>
25: </body>
Stacktrace:] with root cause
java.lang.Exception: Errore nella stringa
at org.apache.jsp.send_jsp._jspService(send_jsp.java:113)
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:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)
This is the method showContent with it's called methods:
public static String showContent() throws Exception {
if (isFood())
return getContent();
else
return "LOG Creato: " + generateLogFile();
}
private static String generateLogFile() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String logname = "foodLog_" + sdf.format(cal.getTime());
String logdir = ps.getProperty("logfolder");
File f = new File ("." + logdir + logname + ".log");
FileOutputStream fout = new FileOutputStream(f);
DataOutputStream dout = new DataOutputStream(fout);
System.out.println(logname);
System.out.println(logdir);
System.out.println(f.getParent());
dout.writeBytes(food + " non esistente, si prega di aggiungerlo");
fout.close();
return logname;
}
private static String getContent() {
String result = "{[";
#SuppressWarnings("resource")
Scanner sc = new Scanner(inputReader).useDelimiter("\\A");
result += sc.hasNext() ? sc.next() : "";
return result;
}
I solved:
showContent() throws an Exception, and I only need to catch that.
The error was caused because I used to throw a new exception in the try-catch of showContent(), something I couldn't do for the reason above.
Thanks everybody.

Categories

Resources