思路:在spring-mvc.xml中配置拦截器,拦截请求并增加返回头"Access-Control-Allow-Origin", “*”
1.spring-mvc.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!-- 拦截路径 -->
<bean class="com.gss.fruitmall.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
2.myInterceptor
package com.gss.fruitmall.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 MyInterceptor 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 {
}
}