AJAX跨域访问如何再服务器中添加过滤器

Posted 张家欢。。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX跨域访问如何再服务器中添加过滤器相关的知识,希望对你有一定的参考价值。

1.再工程文件中新建filter

package com.TestFilter;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class TestFilter
 */
@WebFilter("/TestFilter")
public class TestFilter implements Filter {

    /**
     * Default constructor. 
     */
    public TestFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
         HttpServletResponse response = (HttpServletResponse)servletResponse;       
         response.setHeader("Access-Control-Allow-Origin","*");       
         response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,OPTIONS");      
         response.setHeader("Access-Control-Allow-Credentials","true");       
         chain.doFilter(request, response);       
         System.out.println(" **********************CROS  执行了 **********************");  
        }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

2.在web.xml中配置相

1 <filter>        
2    <filter-name>TestFilter</filter-name>        
3    <filter-class>com.TestFilter.TestFilter</filter-class>   
4 </filter>    
5 <filter-mapping>       
6      <filter-name>TestFilter</filter-name>       
7      <url-pattern>/*</url-pattern>   
8 </filter-mapping>

 

应的拦截路径

 

以上是关于AJAX跨域访问如何再服务器中添加过滤器的主要内容,如果未能解决你的问题,请参考以下文章

ajax跨域访问数据

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

如何解决IE8下Ajax调用时跨域的问题

SpringBoot学习-SpringBoot添加支持CORS跨域访问

Ajax的问题(跨域)

ajax跨域