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

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);
    });

你可能感兴趣的:(java,JavaScript)