【发布时间】:2012-02-20 11:49:28
【问题描述】:
这将使用 临时 302 HTTP 状态代码重定向请求:
HttpServletResponse response;
response.sendRedirect("http://somewhere");
但是是否可以使用 永久 301 HTTP 状态码来重定向它?
【问题讨论】:
这将使用 临时 302 HTTP 状态代码重定向请求:
HttpServletResponse response;
response.sendRedirect("http://somewhere");
但是是否可以使用 永久 301 HTTP 状态码来重定向它?
【问题讨论】:
您需要手动设置响应状态和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();
我使用了以下代码,但没有为我工作。
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);
这对我有用,我遇到了同样的问题
【讨论】: