zoukankan      html  css  js  c++  java
  • 前后端分离项目,支持跨域,session不丢失

    备用:

    在调试一个前后端分离的项目,发现登录成功后已经把信息保存到session中了,再从session中取得当前用户信息的时候发现取不到,debug发现sessionId已经变了,自己网上查了很多资料,并不准确,

    把自己的解决分享给大家:

    后端拦截器:

    //拦截器添加跨域支持(如果是web.xml配置拦截器,请将@component删除)
    //@Component
    public class CORSFilter implements Filter {
    
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            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跨域
            filterChain.doFilter(servletRequest, servletResponse);
    
        }
    
        @Override
        public void destroy() {
    
        }
    }

    关键点:

     response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

     response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域


    前段代码:

    request: function(param) {
        var _this = this;
        $.ajax({
           xhrFields: {
               withCredentials: true
    },
            type: param.method || 'get',
            url: param.url || '',
            dataType: param.type || 'json',
            data: param.data || '',
            success: function(res) {
                console.log("网络请求结果:"+res.toString());
                //请求成功
               
    
            },
            error: function(err) {
                typeof param.error === 'function' && param.error(err.statusText);
            }
        });
    },

    关键点:

        在ajax请求中增加

          xhrFields: {
               withCredentials: true
           },

  • 相关阅读:
    Castle 1.0 RC2 尝鲜
    关注 Web Client Software Factory [Weekly Drop 08]
    ASP.NET AJAX入门系列
    Castle 1.0 Release Candidate 2发布
    ASP.NET AJAX入门系列(2):使用ScriptManager控件
    ASP.NET AJAX 1.0 Beta 发布相关文章总结及推荐
    关于ASP.NET AJAX的三个视频
    企业库2.0培训系列课程大纲[意见征询]
    Visual Studio“Orcas”October 2006 CTP版下载
    ASP.NET AJAX入门系列(4):使用UpdatePanel控件(一)
  • 原文地址:https://www.cnblogs.com/bigbigzhao/p/14373707.html
Copyright © 2011-2022 走看看