zoukankan      html  css  js  c++  java
  • 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>

    应的拦截路径

  • 相关阅读:
    jsonrpc
    第十章:多线程
    第九章:IO流
    第八章:集合
    第七章:常用类
    第六章:异常机制
    第四章:数组
    第三章:流程控制语句
    第二章:数据类型和运算符
    第五章:面向对象4
  • 原文地址:https://www.cnblogs.com/ZHANG576433951/p/12542002.html
Copyright © 2011-2022 走看看