tomcat允许跨域请求:

时间:2023-03-08 15:14:16
tomcat允许跨域请求:

在springmvc-servlet.xml中配置
<mvc:interceptors>

<bean class="com.read.api.pc.interceptor.CrossDomainInterceptor" />

<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->

</mvc:interceptors>

com.read.api.pc.interceptor新建CrossDomainInterceptor.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class CrossDomainInterceptor implements HandlerInterceptor {

@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse reponse, Object arg2, Exception arg3) throws Exception {

reponse.setHeader("Access-Control-Allow-Origin", "*");
}

@Override
public void postHandle(HttpServletRequest req, HttpServletResponse reponse, Object arg2, ModelAndView arg3) throws Exception {

reponse.setHeader("Access-Control-Allow-Origin", "*");
}

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
arg1.setHeader("Access-Control-Allow-Origin", "*");
return true;
}

}
如果只允许某一个接口支持跨域请求:
@RequestMapping("doorDesign/index/add.do")
@ResponseBody
public String add(HttpServletRequest req, HttpServletResponse rsp,
DoorDesignEntity doorDesign, String name,String phone, String province,
String city ){
rsp.setHeader("Access-Control-Allow-Origin", "*");//允许跨域
return service.add(req, rsp, doorDesign, name, phone, province, city);
}