Springmvc-跨域请求-后端设置)

最近在开发UIAPP的项目,出现了文件上传,请求出现跨域问题,在后台进行了相应的设置,因为项目本身的框架是Spring-MVC,所以使用的配置过滤器的方案,供各位参考

1. web.xml 配置


  <filter>
    <filter-name>crossFilter</filter-name>
    <filter-class>com.cd.filter.CrossFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>crossFilter</filter-name>
    <url-pattern>/* </url-pattern>
  </filter-mapping>
  
  • filter-class 为过滤器实现类的路径,看自己包的位置改一下
  • url-pattern 为过滤的路径,我设置的为所有路径,根据自己情况设定

2. 过滤器实现类

/**
 * @author 隐形的稻草人 by 2020-7-1 15:00:14
 */
public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String origin = req.getHeader("Origin");
        if(!org.springframework.util.StringUtils.isEmpty(origin)) {
            res.addHeader("Access-Control-Allow-Origin", origin);
        }
        res.addHeader("Access-Control-Allow-Methods", "*");
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Headers", "content-type");
        res.addHeader("Access-Control-Allow-Headers", "Authorization");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

上文为本程序猿小学生在项目开发过程中的一些问题解决方案,仅供参考,不喜勿喷,欢迎评论交流!

上一篇:使用mybatis 过程中遇到的报错的坑


下一篇:关于struts的ognl表达式