Spring配置跨域请求
发布时间:2020-12-15 07:13:08 所属栏目:Java 来源:网络整理
导读:本文主要是Spring+SpringMVC+MyBatis/MyBatis Plus框架环境,包括SpringBoot同样适用。 1.编写拦截器 package com.interceptor; import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; org.springframework.web.servlet.H
本文主要是Spring+SpringMVC+MyBatis/MyBatis Plus框架环境,包括SpringBoot同样适用。 1.编写拦截器 package com.interceptor; import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; org.springframework.web.servlet.HandlerInterceptor; org.springframework.web.servlet.ModelAndView; public class CORSInterceptor implements HandlerInterceptor { @Override boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception { response.addHeader("Access-Control-Allow-Origin","*"); return true; } @Override void postHandle(HttpServletRequest request,Object handler,ModelAndView modelAndView) Exception { } @Override afterCompletion(HttpServletRequest request,Exception ex) 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> function test(){ var str="test; $.ajax({ url:http://192.168.1.125:8080/test-web/user/getCookie,type:POSTstr:str},dataType : 'json(data){ alert(data.returnMsg); },error:(XMLHttpRequest,textStatus,errorThrown){ alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); } </body onload="test()"body> ? 在没有配置拦截器的情况下,会出现如下结果: ? 配置了拦截器则会正常返回对应的信息。 ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |