【问题标题】:HttpServletResponse sendRedirect permanentHttpServletResponse sendRedirect 永久
【发布时间】:2012-02-20 11:49:28
【问题描述】:

这将使用 临时 302 HTTP 状态代码重定向请求:

HttpServletResponse response;
response.sendRedirect("http://somewhere");

但是是否可以使用 永久 301 HTTP 状态码来重定向它?

【问题讨论】:

    标签: java servlets


    【解决方案1】:

    您需要手动设置响应状态和Location标头。

    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", "http://somewhere/");
    

    sendRedirect() 之前设置状态将不起作用,因为sendRedirect() 之后会将其覆盖为SC_FOUND

    【讨论】:

    • Sends a temporary redirect response to the client using the specified redirect location URL. 好的 - 你是对的。我实际上认为它的行为类似于设置状态后与 sendError 一起使用的方式。因此,我的帖子中的“尝试设置”xD
    • sendError() 将状态作为参数,sendRedirect() 不是。无论当前状态如何,它都会隐式设置 302。
    • 谢谢,这行得通。要提交响应,您还必须刷新缓冲区:response.flushBuffer();
    • @k12345:容器应该隐式执行此操作。实际上,您不需要向响应正文中写入任何内容。
    • @egemen:可能没有必要。在设置响应状态(例如,转发到某个 JSP 而不是从方法返回)之后,您错误地继续代码流,或者您在服务器中遇到了错误。在这种情况下,向 servletcontainer 的供应商报告问题。
    【解决方案2】:

    我使用了以下代码,但没有为我工作。

    String newURL = res.encodeRedirectURL("...");
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.sendRedirect(newURL);
    

    然后我尝试了这段对我有用的代码

    String newURL = res.encodeRedirectURL("...");
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", newURL);
    

    这对我有用,我遇到了同样的问题

    how to set status to 301 while redirecting

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2015-06-26
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 2021-12-25
      相关资源
      最近更新 更多