• Spring配置跨域请求


    本文主要是Spring+SpringMVC+MyBatis/MyBatis Plus框架环境,包括SpringBoot同样适用。

    1.编写拦截器

    package com.interceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    public class CORSInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
                                 Object handler) throws Exception {
    
            response.addHeader("Access-Control-Allow-Origin", "*");
            
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                                    Object handler, Exception ex) throws Exception {
    
        }
    }

    2.在spring-mvc.xml文件配置拦截器

      <mvc:interceptors>
               <mvc:interceptor>
                <mvc:mapping path="/**"/>
                    <bean class="com.interceptor.CORSInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>

    3.编写html代码测试

    <html>
    
    <head>
        <meta charset="utf-8">
    <script src="jquery-1.8.0.min.js"></script>
    <script>
    function test(){
    var str="test";
    $.ajax({
            url:"http://192.168.1.125:8080/test-web/user/getCookie",
            type:"POST",
            data : {"str":str},
            dataType : 'json',
            success:function(data){
                
                alert(data.returnMsg);
                
            },error:function(XMLHttpRequest, textStatus, errorThrown){
                 alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            }
        });
    }
    </script>
    </head>
    <body onload="test()">
    </body>

    在没有配置拦截器的情况下,会出现如下结果:

    配置了拦截器则会正常返回对应的信息。

  • 相关阅读:
    最全Linux应急响应技巧
    2016年总结
    idapython实现动态函数调用批量注释
    CVE-2015-7645 analyze and exploit
    CVE-2010-3654分析及利用
    apt28组织新的flash漏洞利用包dealerschoice分析
    Spartan Exploit Kit分析
    the beginner's guide to idapython
    一个windows下的ddos样本
    locky勒索样本分析
  • 原文地址:https://www.cnblogs.com/youcong/p/9676433.html
Copyright © 2020-2023  润新知