Java跨域访问sessionid不一致问题处理

导语:直接上处理方法,具体原理请自行查阅资料.(共用两种方法解决)

常见情景:设置进session中的值,在第二次请求时获取出来的是:null

第一种方法:针对请求较少的需求:

一.服务器段:

设置可以支持跨域请求:

  response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      /*  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");*/
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨

@RestController
@CrossOrigin(origins = "http://127.0.0.1:8080",maxAge = 3600)
@RequestMapping("/login")
//@SessionAttributes(value="validCode")
public class LoginController {
    @Autowired
    private LoginServer loginServer;
    @RequestMapping(value = "in" ,method = RequestMethod.POST)
    public void login(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      /*  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");*/
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
        Login user=null;
        JSONObject obj=new JSONObject();
        PrintWriter out=response.getWriter();
        String code=request.getParameter("code");
        String username=request.getParameter("username");
        String pwd=request.getParameter("pwd");
        session=request.getSession();
       String validCode=(String) session.getAttribute("validCode");

2.客户端

在ajax请求中添加可以支持携带cookie;

xhrFields:{
    withCredentials:true //允许携带cookie
},
 $.ajax({
          type:"post",
          url:"http://127.0.0.1:8081/service/login/in",
          xhrFields:{
              withCredentials:true
          },
          data:{
              username:$("#username").val(),
              pwd:$("#pwd").val(),
              code:$("#code").val()
          },
          dataType:"json",
          success:function (data) {
           if(data.pass){
               window.location.href="index.html";

           }else{
              layer.alert(data.msg)
           }
          }
      })

第二种方法:针对请求较多的需求,利用过滤器实现:

一.服务器创建过滤器(过滤器中设置请求头部):

package com.ssm.fileter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrossDomainFilter implements Filter {
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //设置跨域请求
        HttpServletResponse response = (HttpServletResponse) res;
        //此处ip地址为需要访问服务器的ip及端口号
        response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,Token,Accept, Connection, User-Agent, Cookie");
        response.setHeader("Access-Control-Max-Age", "3628800");

      //  System.out.println("设置跨域请求");
        chain.doFilter(req, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }
}

二.在web.xml中引入过滤器

 
  
    crossFilter
    com.ssm.fileter.CrossDomainFilter
  
  
    crossFilter
    /*
  

三.客户端:设置请求可以携带cookie

 $.ajax({
          type:"post",
          url:"http://127.0.0.1:8081/service/login/in",
          xhrFields:{
              withCredentials:true
          },
          data:{
              username:$("#username").val(),
              pwd:$("#pwd").val(),
              code:$("#code").val()
          },
          dataType:"json",
          success:function (data) {
           if(data.pass){
               window.location.href="index.html";

           }else{
              layer.alert(data.msg)
           }
          }
      })

你可能感兴趣的:(Spring,MVC)