问题描述
您已经在catch代码块中转发了响应:
RequestDispatcher dd = request.getRequestDispatcher("error.jsp");
dd.forward(request, response);
因此,您不能再次调用:
response.sendRedirect("usertaskpage.jsp");
因为它已经转发(提交)。
因此,您可以做的是:保留一个字符串以分配需要转发响应的位置。
String page = "";
try {
} catch (Exception e) {
page = "error.jsp";
} finally {
page = "usertaskpage.jsp";
}
RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);
解决方法
我正在尝试使用以下代码将值从servlet传递到jsp页面:
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();
}
}
当我运行页面时,我得到:
错误:
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)
我尝试使用:
RequestDispatcher dd=request.getRequestDispatcher("usertaskpage.jsp");
dd.forward(request,response);
但是我遇到了同样的错误。
如何解决这个错误?