springboot 处理请求的小分支-跳转 & cookie

首先是跳转,应该说设置状态,其中跳转是其中一个状态,

1
2
3
4
@RequestMapping(value = "request1", method = RequestMethod.GET)
public void request1(HttpServletRequest request, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
}

200 状态就很简单,如果想做跳转可以使用 302 并设置 location

1
2
3
4
5
@RequestMapping(value = "request2", method = RequestMethod.GET)
public void request2(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Location", "https://baidu.com");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
}

这里如果设置了 302,但没设置跳转 location,就是 302 found

1
2
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;

而如果是 301 跳转,代表原地址不可用了,永久跳转

1
2
3
4
5
@RequestMapping(value = "request3", method = RequestMethod.GET)
public void request3(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Location", "https://baidu.com");
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
}

另一个问题是设置 cookie

1
2
3
4
5
6
@RequestMapping(value = "request4", method = RequestMethod.GET)
public void request4(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = new Cookie("a", "b");
response.addCookie(cookie);
response.setStatus(HttpServletResponse.SC_OK);
}

这样的设置就能成功设定 cookie,而随着目前的浏览器 cookie 策略,如果要跳转后设置的话,估计是会越来越难,包括

1
response.addHeader("Set-Cookie", "a=b; domain=baidu.com; SameSite=none;Secure");

这样的方式也没法实现。