java Servlet IllegalStateException:在提交响应后无法调用sendRedirect()

时间:2017-01-21 10:39:03

标签: java servlets

为什么我不知道,但请考虑以下代码,

package net.collanomics.servlet.auth;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutAccess extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
    checkAccess(req,res);
    HttpSession session=req.getSession(false);
    session.removeAttribute("id");
    session.removeAttribute("name");
    session.invalidate();
    res.sendRedirect("/hello-world/login");

}
public void checkAccess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
    HttpSession session=req.getSession(false);
    if(session!=null){
        res.sendRedirect("/hello-world/login");
    }
}
}

我得到这样的例外“ HTTP状态500 - 在提交响应后无法调用sendRedirect()”。并完成printStackTrace,如下所示: -

type Exception report

message Cannot call sendRedirect() after the response has been committed

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:488)
net.collanomics.servlet.auth.LogoutAccess.doGet(LogoutAccess.java:18)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.5.9 logs.

我想知道导致此错误的原因是什么以及我如何修复该错误。

...谢谢

0 个答案:

没有答案