跨域传session还是不行为什么?

package com.miaoshaproject.controller;

import com.alibaba.druid.util.StringUtils;
import com.miaoshaproject.controller.viewobject.UserVO;
import com.miaoshaproject.error.BusinessException;
import com.miaoshaproject.error.EmBusinessError;
import com.miaoshaproject.response.CommonReturnType;
import com.miaoshaproject.service.UserService;
import com.miaoshaproject.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Controller("user")
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class UserController extends BaseController{
    @Autowired
    UserService userService;
    @Autowired
    private HttpServletRequest httpServletRequest;
    //用户注册接口
    @RequestMapping(value = "/register",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType register(@RequestParam(name = "telphone")String telphone,
                                     @RequestParam(name = "otpCode")String otpCode,
                                     @RequestParam(name = "name")String name,
                                     @RequestParam(name = "gender")Integer gender,
                                     @RequestParam(name = "age")Integer age,
                                     @RequestParam(name = "password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //验证手机号和对应的otpCode相符合
        String inSessionOtpCode = (String)this.httpServletRequest.getSession().getAttribute("telphone");
        if (!StringUtils.equals(otpCode,inSessionOtpCode)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"短信验证码不符合");
        }
        //用户的注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncptPassword(this.EncodeByMd5(password));

        userService.register(userModel);
        return CommonReturnType.create(null);
    }

    public String EncodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密字符串
        String newStr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newStr;
    }
    //用户获取OTP验证码
    @RequestMapping(value = "/getotp",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name = "telphone")String telphone){
        //需要按照一定规则生成OTP验证码
        Random random = new Random();
       int randomInt = random.nextInt(99999);
       randomInt+=10000;
       String otpCode = String.valueOf(randomInt);

        //将OTP验证码与用户手机号关联,使用httpsession的方式绑定他的手机号与OTPCODE
        httpServletRequest.getSession().setAttribute(telphone,otpCode);
        //将OTP验证码通过短信通道发送给用户,省略
        System.out.println("telphone="+telphone+"&otpCode="+otpCode);
        return CommonReturnType.create(null);
    }
    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getUser(@RequestParam(name = "id")Integer id) throws BusinessException {
        //调用service服务层调取对象
       UserModel userModel =  userService.getUserById(id);
       //若获取的对应用户信息不存在
        if (userModel == null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
       UserVO userVO = convertFromUserModel(userModel);
       return CommonReturnType.create(userVO);
    }
    private UserVO convertFromUserModel(UserModel userModel){
        if (userModel == null){
            return  null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel,userVO);
        return userVO;
    }


}
<!DOCTYPE html><html><head>	<meta charset="utf-8">	<script href="bootstrap.css" rel="stylesheet" type="text/css"></script>	<script src="jquery-3.3.1.js"></script></head><body class="login">	<div class="content">		<h3 class="form-title">获取otp信息</h3>		<div>			<label>手机号</label>			<div>				<input type="text" placeholder="手机号" name="telphone" id="telphone"/>			</div>		</div>		<div>			<button id="register" type="submit">				获取otp短信			</button>		</div>	</div></body><script>	jQuery(document).ready(function(){		//绑定otp的click事件,用于后端发送获取手机验证码的请求		$("#register").on("click",function(){			var telphone = $("#telphone").val();			if (telphone==null || telphone =="") {				alert("手机号不能为空");				return false;			}			$.ajax({				type:"POST",				contentType:"application/x-www-form-urlencoded",				url:"http://localhost:8080/user/getotp",				data:{					"telphone":$("#telphone").val(),				},				xhrFields:{withCredentials:true},				success:function(data){					if (data.status=="success") {						alert("otp已经发送到您的手机上,请注意查收");						window.location.href="file:///C:/Users/shenyijie/Documents/html/register.html";					}else{						alert("otp发送失败,原因为"+data.data.errMsg);					}				},				error:function(data){					alert("otp发送失败,原因是"+data.responseText);				}			});			return false;		});	});</script></html>
<!DOCTYPE html><html><head>	<meta charset="utf-8">	<script href="bootstrap.css" rel="stylesheet" type="text/css"></script>	<script src="jquery-3.3.1.js"></script></head><body class="login">	<div class="content">		<h3 class="form-title">用户注册</h3>		<div>			<label>手机号</label>			<div>				<input type="text" placeholder="手机号" name="telphone" id="telphone"/>			</div>		</div>		<div>			<label>验证码</label>			<div>				<input type="text" placeholder="验证码" name="otpCode" id="otpCode"/>			</div>		</div>		<div>			<label>用户昵称</label>			<div>				<input type="text" placeholder="用户昵称" name="name" id="name"/>			</div>		</div>		<div>			<label>性别</label>			<div>				<input type="text" placeholder="性别" name="gender" id="gender"/>			</div>		</div>		<div>			<label>年龄</label>			<div>				<input type="text" placeholder="年龄" name="age" id="age"/>			</div>		</div>		<div>			<label>密码</label>			<div>				<input type="password" placeholder="密码" name="password" id="password"/>			</div>		</div>		<div>			<button id="getotp" type="submit">				提交注册			</button>		</div>	</div></body><script>	jQuery(document).ready(function(){		//绑定otp的click事件,用于后端发送获取手机验证码的请求		$("#getotp").on("click",function(){			var telphone = $("#telphone").val();			var age = $("#age").val();			var gender = $("#gender").val();			var name = $("#name").val();			var password = $("#password").val();			var otpCode = $("#otpCode").val();			if (telphone==null || telphone =="") {				alert("手机号不能为空");				return false;			}			if (password==null || password =="") {				alert("密码不能为空");				return false;			}			if (age==null || age =="") {				alert("年龄不能为空");				return false;			}			if (gender==null || gender =="") {				alert("性别不能为空");				return false;			}			if (otpCode==null || otpCode =="") {				alert("验证码不能为空");				return false;			}			$.ajax({				type:"POST",				contentType:"application/x-www-form-urlencoded",				url:"http://localhost:8080/user/register",				data:{					"telphone":$("#telphone").val(),					"password":$("#password").val(),					"age":$("#age").val(),					"gender":$("#gender").val(),					"otpCode":$("#otpCode").val(),					"name":$("#name").val(),				},				xhrFields:{withCredentials:true},				success:function(data){					if (data.status=="success") {						alert("注册成功");					}else{						alert("注册失败,原因为"+data.data.errMsg);					}				},				error:function(data){					alert("注册失败,原因是"+data.responseText);				}			});			return false;		});	});</script></html>

照着老师写的,自己看了好多遍,没错,调试也是正确插入了session,但是跨域获取的时候还是null

慕神6073059
浏览 1448回答 1
1回答

OneKi

浏览器按F12看看是否传参了,后端Debug一下看接受到参数没有
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java