zoukankan      html  css  js  c++  java
  • SpringMVC处理ajax请求的跨域问题和注意事项

     .首先要知道ajax请求的核心是JavaScrip对象和XmlHttpRequest,而浏览器请求的核心是浏览器我的个人博客(基于SSM,Redis,Tomcat集群的后台架构)

    github:https://github.com/liqianggh

    ajax请求

    浏览器请求

    场景一:使用ajax获取session中的user(跨域)

    从上图可知,ajax每次访问服务器时都没有携带cookie,所以服务器每次都会分配一个新的session对象,所以ajax默认请求是直接获取不了session中的数据的。因此,如果我们想要通过ajax获取当前浏览器的session,我们必须保证每次发送请求都要携带cookie以确保获取的事统一个session。

    解决方法:step1.服务器设置接收ajax发送的cookie

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    //HandlerInterceptorAdapter
    //跨域设置
    public class CrossInterceptor extends HandlerInterceptorAdapter {    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.addHeader("Access-Control-Allow-Origin","http://localhost:8080"); response.addHeader("Access-Control-Allow-Methods","*"); response.addHeader("Access-Control-Max-Age","100"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); //允许客户端发送cookies true表示接收,false不接受 默认为false? response.addHeader("Access-Control-Allow-Credentials","true"); return super.preHandle(request, response, handler); } }

    step2 。设置ajax请求携带cookie

        $.ajax({
            url: url+'/checkout.action',
            type: 'GET',
            dataType: '',
            data: {verifyCode: VerificationCodeInput.value},
            //添加跨域
           async: false,  
            xhrFields: {  
                withCredentials: true  
            },  
            crossDomain: true,  
            success:function(data){
                console.log(data);
            }
        });

    注: xhrFields: { withCredentials: true }, crossDomain: true, 一定要加上!!!!

    这样就可以愉快的玩耍了!

    场景二:当用户需要校验session是否登陆(没有登陆跳转到登陆页面)

    基于场景一,已经解决了回话问题但是在使用SpringMVC中

       request.getRequestDispatcher(xxxx.html").forward(request, response);
         response.sendRedirect("http://www.baidu.com");

    会报错。因为当服务器转发或者重定向时返回的是一个页面,因为只有浏览器才能解析显示页面,而ajax的对象却不能,所以会报错错。

    解决办法:因为ajax请求对象不能解析显示页面,所以不能直接转发或重定向,这时我们需要绕过服务器,直接使用浏览器跳转页面,但是对于session过期(用户没有登陆)我们要给浏览器一个反馈,我们可以给浏览器一个大于等于600的错误码

          String requestType = request.getHeader("X-Requested-With");
            if(requestType != null && "XMLHttpRequest".equalsIgnoreCase(requestType.trim())) {
                //如果是ajax请求就设置一个自定义响应头
                response.setHeader("sessionStatus", "timeout");
            //设置错误码以及错误码提示 response.sendError(
    666, "session timeout"); return false; }

     同时要对ajax设置全局options

    $.ajaxSetup({
      type:'post',
      complete:function(xhr, ts){ //XMLHttpRequest, textStatus
          var sessionStatus = xhr.getResponseHeader('sessionstatus');
          if(sessionStatus == 'timeout') {
              alert('用户没有登陆,请登录!');
              window.top.location.href = 'Login.html';
          }
      }
    });

     这样就可以通过浏览器进行页面跳转了!

  • 相关阅读:
    洛谷P2894 [USACO08FEB]酒店Hotel
    codevs 3981 动态最大子段和
    舞蹈家怀特先生(线型)
    IOS8 通知中心(Notification Center)新特性
    WWDC2014 IOS8 APP Extensions
    IOS8 TouchID使用介绍
    IOS8 UIAlertController 弹框
    Unable to run Kiwi tests on iOS8 device
    registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later
    iOS开发---- 开发错误汇总及解决方法
  • 原文地址:https://www.cnblogs.com/liqiangchn/p/7868785.html
Copyright © 2011-2022 走看看