gpt4 book ai didi

java - 提交响应后如何解决无法调用 sendRedirect() 的问题?

转载 作者:IT老高 更新时间:2023-10-28 21:00:34 32 4
gpt4 key购买 nike

我正在尝试使用以下代码将值从 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);

但我遇到了同样的错误。

如何解决这个错误?

最佳答案

您已经在 catch block 中转发了响应:

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);

关于java - 提交响应后如何解决无法调用 sendRedirect() 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352632/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com