前后端分离中使用 Session 域传输对象
前提前端使用 Vue,后端使用 SpringBoot 框架,使用 Session 传值后端获取不到。这里使用 Session 域来存储验证码,拿到后台去比对,验证是否正确。前端代码如下,只是发送一个请求:/*** 加载验证码*/loadImageCode() {let _this = this;_this.imageCodeToken = Tool.uuid(8);$('#image-code')
·
前提
前端使用 Vue,后端使用 SpringBoot 框架,使用 Session
传值后端获取不到。
这里使用 Session 域来存储验证码,拿到后台去比对,验证是否正确。
前端代码如下,只是发送一个请求:
/**
* 加载验证码
*/
loadImageCode() {
let _this = this;
_this.imageCodeToken = Tool.uuid(8);
$('#image-code').attr('src', process.env.VUE_APP_SERVER + '/system/admin/kaptcha/image-code/' + _this.imageCodeToken);
},
login() {
let _this = this;
// 如果密码是从缓存带出来的: 则不需要重新加密
let md5 = hex_md5(_this.user.password);
let rememberUser = LocalStorage.get(LOCAL_KEY_REMEMBER_USER) || {};
if (md5 !== rememberUser.md5) {
_this.user.password = hex_md5(_this.user.password + KEY);
}
_this.user.imageCodeToken = _this.imageCodeToken;
Loading.show();
_this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/user/login', _this.user).then(response => {
Loading.hide();
let resp = response.data;
if (resp.success) {
// resp.content: {id: "wAtUSitS", loginName: "test", name: "test"}
let cont = resp.content;
Toast.success('登陆成功');
····
后端是这样的:
@GetMapping("/image-code/{imageCodeToken}")
public void imageCode(@PathVariable(value = "imageCodeToken") String imageCodeToken, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception{
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// 生成验证码字符串
String createText = defaultKaptcha.createText();
request.getSession().setAttribute(imageCodeToken, createText);
····
/**
* 登陆
*
* @param userDto userDto
* @return 返回响应
*/
@PostMapping("/login")
public ResponseDto<LoginUserDto> login(@RequestBody UserDto userDto, HttpServletRequest request) {
LOG.info("用户登陆开始");
// MD5 加密
userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
ResponseDto<LoginUserDto> responseDto = new ResponseDto<>();
// 根据验证码 token 去获取缓存中的验证码 判断和用户输入的验证码是否一致
String imageCode = (String) request.getSession().getAttribute(userDto.getImageCodeToken());
if (StringUtils.isEmpty(imageCode)) {
responseDto.setSuccess(false);
responseDto.setMessage("验证码已过期");
LOG.info("用户登陆失败: 验证码已过期");
return responseDto;
}
if (!imageCode.toLowerCase().equals(userDto.getImageCode().toLowerCase())) {
responseDto.setSuccess(false);
responseDto.setMessage("验证码不对");
LOG.info("用户登录失败: 验证码不对");
return responseDto;
} else {
// 验证码通过后 移除验证码
request.getSession().removeAttribute(userDto.getImageCodeToken());
}
····
解决
在 Vue 的 main.js 中添加这一句:
// 解决每次 ajax 请求, 对应的 sessionId 不一致的问题
axios.defaults.withCredentials = true;
同时设置一下跨域
,这里给出一种方法,其他方法请看这篇文章 https://blog.csdn.net/weixin_43941364/article/details/109004806:
更多推荐
已为社区贡献4条内容
所有评论(0)