tomcat跨域的若干实现总结

1、tomcat级别

这种方法是修改CATALINA_HOME/conf/web.xml文件,在其中添加如下配置:

<filter>
       <filter-name>CorsFilter</filter-name>
       <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
       <init-param>
           <param-name>cors.allowed.origins</param-name>
           <param-value>*</param-value>
          </init-param>
  </filter>
  <filter-mapping>
          <filter-name>CorsFilter</filter-name>
          <url-pattern>/xxx/*</url-pattern>
  </filter-mapping>

同时需要将两个jar添加进 CATALINA_HOME/lib目录:

cors-filter-2.5.jar和 java-property-utils-1.10.jar


但是这是一种全局性的配置,针对整个tomcat的,所以不建议这么做。


2、servlet级别

首先修改web.xml文件,添加一个filter:

	<filter>
		<filter-name>cors</filter-name>
		<filter-class>cn.xx.CrossFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>cors</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
然后自己实现这个filter:

public class CorsFilter extends OncePerRequestFilter {
    private CorsProcessor processor = new DefaultCorsProcessor();
    private final CorsConfigurationSource configSource;

    public CorsFilter(CorsConfigurationSource configSource) {
        this.configSource = configSource;
    }

    public void setCorsProcessor(CorsProcessor processor) {
        Assert.notNull(processor, "CorsProcessor must not be null");
        this.processor = processor;
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(CorsUtils.isCorsRequest(request)) {
            CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
            if(corsConfiguration != null) {
                boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
                if(!isValid || CorsUtils.isPreFlightRequest(request)) {
                    return;
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}


3、如果使用spring框架3.X,可以通过一个Interceptor

public class VueInterceptor implements HandlerInterceptor {
    private List<String> allowedUrls;

    public List<String> getAllowedUrls() {
        return allowedUrls;
    }

    public void setAllowedUrls(List<String> allowedUrls) {
        this.allowedUrls = allowedUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        String ip = "";
        Enumeration<String> requestHeaderNames = httpServletRequest.getHeaderNames();
        List<String> origins = Arrays.asList(new String[]{"origin", "Origin", "ORIGIN"});
        while(requestHeaderNames.hasMoreElements()) {
            String header = requestHeaderNames.nextElement();
            if(origins.contains(header)) {
                ip = httpServletRequest.getHeader(header);
                System.out.println(header);
                break;
            }
        }
	response.setHeader("Access-Control-Allow-Origin", ip);
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept");
        return true;
    }
}
然后在xml添加以下代码:

<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**" />
			<bean class="cn.creditease.ecif.filter.VueInterceptor">
				<property name="allowedUrls">
					<list>
						<value>http://localhost:8080</value>
						<value>http://10.100.30.97:8088</value>
						<value>http://10.120.64.118:8088</value>
					</list>
				</property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors>

4、如果使用了Spring 框架4.2及以上版本,可以通过在application.xml中添加以下配置来实现跨域:

<mvc:cors>
        <mvc:mapping path="/**" 
        	allowed-origins="*" 
        	allow-credentials="true" 
        	allowed-methods="GET,POST,OPTIONS"/>
</mvc:cors>


5、 Spring 框架 4.2及以上版本还支持注解的方式,可以在类名或更细粒度的方法名上添加注解

@CrossOrigin(methods = { RequestMethod.GET, RequestMethod.POST }, origins = "*")


6、Spring4.2的全局配置:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins(“*)
            .allowedMethods("POST”, “OPTIONS”)
    }
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值