码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-03-21 20:57:05      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:工程文件   options   tor   ros   color   throws   als   red   pack   

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跨域访问如何再服务器中添加过滤器

标签:工程文件   options   tor   ros   color   throws   als   red   pack   

原文地址:https://www.cnblogs.com/ZHANG576433951/p/12542002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!