java无法写入cookie_Spring Boot无法写出Cookie

问题描述

在使用了前后端分离、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原因。

希望有大神能留言帮忙解惑,万分感谢。

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值