过滤器web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <filter> <filter-name>Demo1Filter</filter-name> <filter-class>filter.Demo1Filter</filter-class> <init-param> <param-name>param1</param-name> <param-value>value在这里呢</param-value> </init-param> </filter> <filter-mapping> <filter-name>Demo1Filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <!-- 没有配置dispatcher就是默认request方式的 --> <dispatcher>FORWARD</dispatcher> <dispatcher>ERROR</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping> </web-app>
一个过滤器Java代码
package filter; import javax.servlet.*; import java.io.IOException; /** * <Description> * @classname Demo1Filter * @author zhouyufei * @taskId: * @version 1.0 * @createDate 2019/11/20 9:19 * @see filter */ public class Demo1Filter implements Filter { private FilterConfig filterConfig; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Demo1过滤前"); System.out.println(filterConfig.getInitParameter("param1")); chain.doFilter(request, response);//放行。让其走到下个链或目标资源中 System.out.println("Demo1过滤后"); // 获取访问地址 String remoteAddr = request.getRemoteAddr(); System.out.println(remoteAddr); // 获取端口 int localPort = request.getLocalPort(); System.out.println(localPort); String localAddr = request.getLocalAddr(); System.out.println(localAddr); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化了"); this.filterConfig = filterConfig; } @Override public void destroy() { System.out.println("销毁了"); } }