码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-03-16 14:02:01      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:import   post   servlet   mon   color   registry   webconfig   res   pre   

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() {
    }

}

 

 

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

标签:import   post   servlet   mon   color   registry   webconfig   res   pre   

原文地址:https://www.cnblogs.com/Gent-Wang/p/8580645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!