【问题标题】:response.sendRedirect shows unwanted HttpStatus 302 instead of 307response.sendRedirect 显示不需要的 HttpStatus 302 而不是 307
【发布时间】:2018-03-19 22:34:34
【问题描述】:

我有一个小测试,它应该返回一个带有 HttpStatus 代码 307 的临时重定向的 HttpStatus。
但它总是返回 302。

@RestController
@RequestMapping(value = "/")
public class Controller {

    @ResponseStatus(HttpStatus.TEMPORARY_REDIRECT ) 
    @RequestMapping(value= "test", method = RequestMethod.GET)
    public void resolveUrl(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.sendRedirect("https://www.google.com");
    }
}

当我查看response.sendRedirect() 的文档时,我可以看到:

使用指定的向客户端发送临时重定向响应 * 重定向位置 URL。

还有documentation of temporary redirect is a 307:

10.3.8 307 临时重定向

请求的资源暂时位于不同的 URI 下。 由于重定向有时可能会改变,客户端应该 继续使用 Request-URI 来处理未来的请求。这个回应是 仅在 Cache-Control 或 Expires 标头指示时可缓存 字段。

(我知道,我不需要 @ResponseStatus(HttpStatus.TEMPORARY_REDIRECT)response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);,但我想表明它也不适用于这些东西!)

但我的测试显示它是 302 而不是 307

java.lang.AssertionError:预期状态: 但原为:

谁能解释一下?

我对此的小测试:

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
public class ControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void test() throws Exception {
        MockHttpServletRequestBuilder requestBuilder = get("/test");
        mvc.perform(requestBuilder).andExpect(status().isTemporaryRedirect())
                .andExpect(redirectedUrl("https://www.google.com"));
    }

}

Complete code can be found at github

【问题讨论】:

标签: java redirect httpresponse http-status-code-302 http-status-code-307


【解决方案1】:

而不是使用 sendRediect ,在响应对象中设置 Location 标头。

    response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);

response.setHeader("位置","https://we.google.com");

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 2020-08-22
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多