在spring项目中配置跨域访问

跨域是老生常谈的问题了,不同域名或者相同域名不同端口都会产生跨域访问的问题。

解决方案

1、在前端用jsonp的方式请求
2、后端设置响应头header
3、用Spring MVC 4.2+的版本,已经内置提供跨域支持(@CrossOrigin注解方式 或者 自己配置下 )

我用的spring mvc4.0所以这里给出第二种方式根据拦截器来实现设置响应头:

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Healist on 2017/1/31.
 */
public class CORSFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {

    }
}

web.xml中


  <filter>
    <filter-name>crossoriginfilter-name>
    <filter-class>com.healist.config.CORSFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>crossoriginfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

我这里是直接用了原生的拦截器来写的,其实spring mvc也封装了自己的拦截器,换汤不换药道理差不多的。

附上spring mvc拦截器的实现:SpringMVC拦截器

你可能感兴趣的:(spring,java)