springMVC前后端分离开发模式下支持跨域请求

1、web.xml中添加cors规则支持(请修改包名)


<filter>
    <filter-name>cors</filter-name>
    <filter-class>com...common.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

 

2、spring.xml中添加CorsMapping(请修改包名)


<!-- 解决跨域问题 -->
<bean class="com...common.filter.WebConfig"/>
 
 

3、创建CorsMapping及CorsFilter类

WebConfig.java如下:(请修改包名)

package com...common.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("PUT", "DELETE", "POST", "GET", "OPTIONS")
                .allowedHeaders("x-requested-with", "Authorization")
                .allowCredentials(false).maxAge(3600);
    }


}

 



SimpleCORSFilter.java如下:(请修改包名)
package com...common.filter;

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

public class SimpleCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Access-Control,Content-Type");
        chain.doFilter(req, res);

    }

    @Override
    public void destroy() {
    }

}

 

 


posted @ 2018-03-16 13:43  不会Coding的王震  阅读(853)  评论(0编辑  收藏  举报