HttpServletResponse sendRedirect 永久

发布于 2024-12-29 18:00:06 字数 189 浏览 0 评论 0原文

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

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

但是是否可以使用永久 301 HTTP 状态代码重定向请求?

This will redirect a request with a temporary 302 HTTP status code:

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

But is it possible to redirect it with a permanent 301 HTTP status code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

失而复得 2025-01-05 18:00:06

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

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

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

You need to set the response status and the Location header manually.

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

Setting the status before sendRedirect() won't work as sendRedirect() would overridde it to SC_FOUND afterwards.

弃爱 2025-01-05 18:00:06

我使用了以下代码,但对我不起作用。

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

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

如何在重定向时将状态设置为301

I used the following code, but didn't worked for me.

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

then I tried this piece of code it worked for me

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

this worked for me, I had the same issue

how to set status to 301 while redirecting

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文