记Spring与跨域

跨域

简单理解就是跨域名 (ip+端口)
在 52liming.com 中向demo.com中发起Ajax请求, 出于安全考虑会进行拦截

参考:

Maven中引入CORS Filter

Spring4.0之前 CORS

CORS 跨域资源共享 Cross-Origin Resource Sharing

实现拦截器方式, (因为这次项目中是用的的spring4.0.2, 所以记录下来)

类似白名单

1. Filter 的实现类 CORSFilter.java

package com.hs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


/**
 * @ClassName: CORSFilter
 * @Description: 跨域过滤,正式部署时如果相同域名下建议不使用
 * @author xiaoming
 * @date 2018/06/29 16:59:46
 */
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig var1) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {}
}

2. web.xml

  <filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.xx.filter.CORSFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

Spring 4.2以后

跨域直接通过注解方式, 因为没有实际使用暂不做说明, 网上有很多

posted @ 2018-08-25 22:27 小鸣的微笔记 阅读(...) 评论(...) 编辑 收藏