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>

 

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

 

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

 

posted @ 2018-09-19 19:06  挑战者V  阅读(4452)  评论(0编辑  收藏  举报