I am trying to pass values from servlet to jsp page using the code below:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
System.out.println("try");
String taskid=request.getParameter("id");
convty = new Connectivity();
con = convty.setConnection();
st=con.createStatement();
query="select * from task_table";
rset=convty.getResultSet(query, con);
while(rset.next()) {
System.out.println("while");
lst.add(rset.getString("task_id"));
lst.add(rset.getString("date"));
lst.add(rset.getString("project_name"));
}
rset.close();
System.out.println("after while");
} catch(Exception e) {
RequestDispatcher dd= request.getRequestDispatcher("error.jsp");
dd.forward(request, response);
} finally {
System.out.println("finally1");
HttpSession sessionvar = request.getSession();
sessionvar.setAttribute("TaskData", "lst");
response.sendRedirect("usertaskpage.jsp");
lst.clear();
out.close();
}
}
when I run my page I am getting:
Error :
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
src.Taskservlet.doPost(Taskservlet.java:108)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
I tried to use:
RequestDispatcher dd=request.getRequestDispatcher("usertaskpage.jsp");
dd.forward(request, response);
but I got the same error.
How to fix this error?
you have already forwarded the response in catch block:
RequestDispatcher dd = request.getRequestDispatcher("error.jsp");
dd.forward(request, response);
so, you can not again call the :
response.sendRedirect("usertaskpage.jsp");
because it is already forwarded (committed).
So what you can do is: keep a string to assign where you need to forward the response.
String page = "";
try {
} catch (Exception e) {
page = "error.jsp";
} finally {
page = "usertaskpage.jsp";
}
RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);