1、登录时设置Cookie,返回给前端浏览器
@PostMapping(value = "/login")
public BaseResponse createAuthenticationToken(@RequestBody GovJwtRequest authRequest, HttpServletResponse response) throws UnsupportedEncodingException {
GovJwtResponse jwtResponse = authService.createAuthToken(authRequest);
//这里设置cookie
CookiesUtils.setCookies(response, BaseConstant.AUTH_JWT, jwtResponse.getJwtToken(), BaseConstant.JWT_TOKEN_VALIDITY);
return BaseResponse.with(Code.SUCCESS, jwtResponse);
}
2、可以从请求中获取Cookie,拦截器或者接口中获取都ok
aString = CookiesUtils.getValue(request, BaseConstant.AUTH_JWT);
3、CookieUtil实现
public class CookiesUtils {
/**
* 设置cookie
*
* @param response
* @param name
* @param value
* @param expired 有效时间(s)
*/
public static void setCookies(HttpServletResponse response, String name, String value, int expired)
throws UnsupportedEncodingException {
value = URLEncoder.encode(value, "utf-8");
Cookie cookies = new Cookie(name, value);
cookies.setMaxAge(expired);
cookies.setPath("/");
response.addCookie(cookies);
}
/**
* 设置cookie
*
* @param response
* @param name
* @param value
*/
public static void setCookies(HttpServletResponse response, String name, String value) {
try {
value = URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
Cookie cookies = new Cookie(name, value);
cookies.setPath("/");
response.addCookie(cookies);
}
public static void deleteCookie(HttpServletResponse response, String key) {
Cookie cookie = new Cookie(key, "");
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* 获得cookie
*
* @param request
* @param name
* @return
*/
public static String getValue(HttpServletRequest request, String name) throws UnsupportedEncodingException {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (Objects.equals(cookie.getName(), name)) {
return URLDecoder.decode(cookie.getValue(), "utf-8");
}
}
return null;
}
4、其他
开发时出现过返回Cookie顺利,但是浏览器中并无该Cookie的情况,原因是前端某个库吞掉了Cookie,注意避坑。
网友评论