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>
应的拦截路径
原文地址:https://www.cnblogs.com/ZHANG576433951/p/12542002.html
时间: 2024-10-13 22:28:16