做过滤器分为两步:
1.做类
实现javax.servlet.Filter接口
在doFilter()方法中编写过滤逻辑
2.做配置
在web.xml中配置<filter>和<filter-mapping>元素
1.做类:
1.1实现javax.servlet.Filter接口
在doFilter()方法中编写过滤逻辑
package com.itnba.maya.test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; 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.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Testfilter implements Filter { private ArrayList<String> list =new ArrayList<>(); @Override public void destroy() { // TODO 自动生成的方法存根 } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO 自动生成的方法存根 HttpServletRequest req = (HttpServletRequest )request;//转换类型,最好很次都转 HttpServletResponse res =(HttpServletResponse)response; HttpSession session=req.getSession(); String path1 = req.getRequestURI();//长路径 String path2 = req.getContextPath();//短路径 String target =path1.substring(path2.length()); if(list.contains(target)==false){//判断是否是可以直接访问的路径 if(session.getAttribute("user")==null)//判断是否登陆 { res.sendRedirect("show.jsp"); } else{ chain.doFilter(req, res); } } else { chain.doFilter(request, res); } } @Override public void init(FilterConfig cfg) throws ServletException { // TODO 自动生成的方法存根 String val=cfg.getInitParameter("allowpage");//获取init param中的内容 String[] arr=val.split(","); list.addAll(Arrays.asList(arr)); } }
2.做配置
在web.xml中配置<filter>和<filter-mapping>元素
<?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" metadata-complete="true"> <filter> <filter-name>testFilter</filter-name> <filter-class>com.itnba.maya.test.Testfilter</filter-class><!--过滤器类的位置--!> <init-param> <param-name>allowpage</param-name><!--在过滤器类中的 init(FilterConfig cfg)方法调用,获取下面的value值--!> <param-value>/show.jsp,/show</param-value> </init-param> </filter> <filter-mapping> <filter-name>testFilter</filter-name> <url-pattern>/*</url-pattern><!--需要过滤的路径 --!> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.xhtml</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>