springMVC作为接口供其他系统使用(判断是否登录),解决跨域

SpringMVC实现接口跨域与登录检查
这篇博客介绍了如何使用SpringMVC来创建一个接口,该接口用于其他系统调用,并且包含了判断用户是否登录的功能。通过设置HTTP响应头,解决了跨域问题,允许特定的请求头和方法。同时,展示了在AJAX请求中配置`withCredentials`以发送凭据,确保了登录状态的传递。

java代码:
    @ResponseBody
    @RequestMapping(value = "/getSession",method = {RequestMethod.GET, RequestMethod.POST})
    public Result getSession(HttpServletRequest request) throws UnsupportedEncodingException{
        String originHeader = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", originHeader);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed","1");
        response.setHeader("XDomainRequestAllowed","1");
        RegisterTable user = (RegisterTable)request.getSession().getAttribute("user");
        if(user!=null){
            return ResultUtils.bulidResult(RESULT_CODE.SUCCESS,user);
        }
        return ResultUtils.bulidResult(RESULT_CODE.FAILED,"请先登录再上传!");
    }


jspAJAX代码:
    $.ajax({
        type: "POST",
        url: "*****",
        dataType: "json",

//关键部分,必须写
        xhrFields: {withCredentials: true},
        success: function (data) {
            console.log(data)
        }
    });

这个也行
   $.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
    $.post("****",function(data) {
        console.log(data);
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值