SpringMVC 跨域问题

跨域:就是你在一个在一个域中访问另一个域中服务器的内容。

 后台解决跨域问题一般两种 一种是将返回的数据以jsonp格式返回。前端通过ajax等前段脚本解析jsonp格式数据。

今天只是解决spirngmvc 后台通过过滤器解决跨域

 

过滤器代码如下:

    public class BasicFilter implements Filter {

     public void destroy() {

     }

     public void doFilter(ServletRequest servletRequest,
   ServletResponse servletResponse, FilterChain filterchain)
   throws IOException, ServletException {

      HttpServletResponse response = (HttpServletResponse) servletResponse;
//  HttpServletRequest request = (HttpServletRequest) servletRequest;
//  HttpSession session = request.getSession();
  

  1. // 指定允许其他域名访问  

  response.addHeader("Access-Control-Allow-Origin", "*");

2、// 响应类型  响应方法

  response.addHeader("Access-Control-Allow-Methods", "POST, OPTIONS"); 

    // 响应头设置 

  response.addHeader("Access-Control-Allow-Headers", "POWERED-BY-FANTONG");

    response.addHeader("Access-Control-Max-Age", "30");   
  
  
  // 需要过滤的代码
  filterchain.doFilter(servletRequest, servletResponse);
 }

     public void init(FilterConfig config) throws ServletException {

     }
}

web.xml中配置过滤器

  <filter>
  <filter-name>basicFilter</filter-name>
  <filter-class>com.fantong.basic.filter.BasicFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>utf-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>basicFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 

你可能感兴趣的:(SpringMVC 跨域问题)