Spring Boot 无法写出 Cookie
Spring Boot Java Cookie 大约 1420 字问题描述
在使用了前后端分离、Spring Security
和Spring Session
的Spring Boot
后端项目(Undertow
作为web
容器)后,当返回的body
包含了中文
且大于15KB
时(不确定是否是这个原因),返回的response header
里没有Set-Cookie
字段,导致前端无法保存SESSION
。
发现问题
在Spring Security
的onAuthenticationSuccess
认证成功后,HttpServletResponse
写出用户信息时使用了PrintWriter
的write(String content)
方法,部分代码如下。
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
PrintWriter printWriter = response.getWriter();
printWriter.write(objectMapper.writeValueAsString(result));
printWriter.flush();
printWriter.close();
}
解决方法
将PrintWriter
的write(String content)
方法替换为response.getOutputStream()
的write(byte[] b)
方法即可。
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
response.getOutputStream().write(objectMapper.writeValueAsBytes(result));
}
具体原因
具体原因目前还没有来得及细追,考虑是Content-Length
计算字符时的问题,因为两个write
方法一个是字节数组,一个是字符串,可能在转换过程中有编码问题。并且使用的web
容器是Undertow
而非Tomcat
,也不确定是Spring Session
还是Undertow
原因。
希望有大神能留言帮忙解惑,万分感谢。
参考
阅读 2403 · 发布于 2020-04-21
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
MySQL 命令行纵向打印阅读 1966
-
VMware Workstation 与 Hyper-V不 兼容阅读 3713
-
SCSS 样式阅读 1574
-
Java WebSocket The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method阅读 3069
-
Docker 运行结束后自动销毁容器阅读 268
-
GoJS 更改 Overview 的拖动框颜色阅读 1067
-
Spring Boot NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory阅读 5108
-
Spring 接口类型 getBeanNamesForType 获取实际类型的流程阅读 1069
-
软考-系统架构设计师:需求分析阅读 1122
-
IDEA 多个 Vue.js 工程识别 Webpack @ 别名阅读 321