tomcat跨域的若干实现总结

Posted LackMemory

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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”)
    








以上是关于tomcat跨域的若干实现总结的主要内容,如果未能解决你的问题,请参考以下文章

如何用CORS来解决JS中跨域的问题

js跨域的各种方法总结。

AJAX实现跨域的三种方法

Java-全局跨域处理

第五节:SignalR大杂烩(与MVC融合全局的几个配置跨域的应用C/S程序充当Client和Server)

AJAX跨域问题总结