Spring Boot实现跨域(转)

一、方法:

  1. 服务端设置Respone Header头中Access-Control-Allow-Origin
  2. 配合前台使用jsonp
  3. 继承WebMvcConfigurerAdapter 添加配置类

二、实例:

后台(spring boot 1.3.7.RELEASE):

1、用一个Filter进行了身份验证同时进行了跨域处理,具体代码:

public class AuthFilter implements Filter {
    //    @Autowired
    //这个不能自动注入servlet和filter是被tomcat管理的
    private BaseUserService baseUserService;
    private String[] excludePaths;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("initFilter");
        //不能在初始化中通过Appliaction Context获取因为这时候还没初始化Application Context
        //baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
        excludePaths = new String[]{"/api/user/noLogin", "/api/user/tokenError", "/api/user/loginForeground",
                "/api/user/loginBackground", "/api/user/inCorrectUserId"};
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //这里填写你允许进行跨域的主机ip
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        //允许的访问方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        //Access-Control-Max-Age 用于 CORS 相关配置的缓存
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        String userId = request.getParameter("userId");
        String token = request.getParameter("token");
        //有token的                                                     `
        if (userId != null && token != null) {
            try {
                Integer id = Integer.parseInt(userId);
                if (baseUserService == null)
                    baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
                int status = baseUserService.checkLogin(id, token);
                if (status == 1) {
                    chain.doFilter(request, response);
                } else if (status == 0) {
                    httpServletResponse.sendRedirect("/api/user/tokenError");
                } else if (status == -2) {
                    httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
                } else {
                    httpServletResponse.sendRedirect("/api/user/noLogin");
                }
            } catch (NumberFormatException exception) {
                httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
            }
        } else {
            String path = httpServletRequest.getServletPath();
            if (excludePath(path)) {
                chain.doFilter(request, response);
            } else {
                httpServletRequest.getRequestDispatcher("/api/user/noLogin").forward(request, response);
            }
        }
//        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
//        CorsFilter corsFilter=new CorsFilter();

    }

    private boolean excludePath(String path) {
        for (int i = 0; i < excludePaths.length; i++) {
            if (path.equals(excludePaths[i]))
                return true;
        }
        return false;
    }

    @Override
    public void destroy() {
        System.out.println("destroy method");
    }

}

这种方法还适用于Servlet中,特别注意的是一定要在Filter动作之前加上这句话,也就是在代码的最前面加上这个话。

2、基于WebMvcConfigurerAdapter配置加入Cors的跨域

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

@Configuration  
public class CorsConfig extends WebMvcConfigurerAdapter {  

    @Override  
    public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**")  
                .allowedOrigins("*")  
                .allowCredentials(true)  
                .allowedMethods("GET", "POST", "DELETE", "PUT")  
                .maxAge(3600);  
    }  

}  

这里有个坑,Spring Boot以前的版本这样设置可以用Filter,但是在1.3.7.RELEASE不能用,所以用第二种方式是万能的。

 

参考:

http://blog.csdn.net/hanghangde/article/details/53946366(以上内容转自此篇文章)

posted @ 2017-10-21 14:21  EasonJim  阅读(12511)  评论(0编辑  收藏  举报