gpt4 book ai didi

java - 提交响应后无法转发 - Servlet

转载 作者:行者123 更新时间:2023-12-01 18:46:58 26 4
gpt4 key购买 nike

我正在尝试从 HTTPSession 注销并将用户重定向到登录页面。

下面是我完整的 Http servlet 代码。

import java.io.IOException;
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 LogoutServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
super.doGet(req, resp);
processRequest(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
super.doPost(req, resp);
processRequest(req, resp);
}

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
final HttpSession session = request.getSession(false);
if (session != null)
{
session.invalidate();
}

response.sendRedirect("/login.html");
//getServletContext().getRequestDispatcher("/login.html").forward(request, response);
}

}

但出现以下异常:

java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.controller.LogoutServlet.processRequest(LogoutServlet.java:41)

最佳答案

删除调用

super.doGet(req, resp); // and
super.doPost(req, resp);

基类实现只是尝试抛出一条不支持 GET 或 POST 的错误消息。

// HttpServlet#doGet() calls
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);

上面的行是已经提交响应的行。

关于java - 提交响应后无法转发 - Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352955/

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