过滤器
过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理
通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理
需要注意的是
过滤器是在服务器启动时就会创建的,只会创建一个实例,常驻内存,也就是说服务器一启动就会执行Filter的init(FilterConfig config)方法.
当Filter被移除或服务器正常关闭时,会执行destroy方法
多个Filter的执行顺序
在我们的请求到达Servle之间是可以经过多个Filter的,一般来说,建议Filter之间不要有关联,各自处理各自的逻辑即可。这样,我们也无需关心执行顺序问题。
如果一定要确保执行顺序,就要对配置进行修改了,执行顺序如下
在web.xml中,filter执行顺序跟的顺序有关,先声明的先执行
使用注解配置的话,filter的执行顺序跟名称的字母顺序有关,例如AFilter会比BFilter先执行
如果既有在web.xml中声明的Filter,也有通过注解配置的Filter,那么会优先执行web.xml中配置的Filter
配置方式
<?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_4_0.xsd"
version="4.0">
<filter>
<filter-name>AFilter</filter-name>
<filter-class>filter.AFilter</filter-class>
</filter>
<filter>
<filter-name>BFilter</filter-name>
<filter-class>filter.BFilter</filter-class>
</filter>
<!--这里BFilter在AFilter之前-->
<filter-mapping>
<filter-name>BFilter</filter-name>
<url-pattern>/admin/jsp/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AFilter</filter-name>
<url-pattern>/filter.jsp</url-pattern>
</filter-mapping>
</web-app>
注解方式
常用配置项
urlPatterns
配置要拦截的资源
以指定资源匹配。例如"/index.jsp"
以目录匹配。例如"/servlet/"
以后缀名匹配,例如".jsp"
通配符,拦截所有web资源。"/*"
initParams
配置初始化参数,跟Servlet配置一样
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
@WebFilter(filterName = "CharsetFilter",
urlPatterns = "/*",/*通配符(*)表示对所有的web资源进行拦截*/
initParams = {
@WebInitParam(name = "charset", value = "utf-8")/*这里可以放一些初始化的参数*/
})
public class CharsetFilter implements Filter {
private String filterName;
private String charset;
public void destroy() {
/*销毁时调用*/
System.out.println(filterName + "销毁");
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
/*过滤方法 主要是对request和response进行一些处理,然后交给下一个过滤器或Servlet处理*/
System.out.println(filterName + "doFilter()");
req.setCharacterEncoding(charset);
resp.setCharacterEncoding(charset);
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
/*初始化方法 接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
filterName = config.getFilterName();
charset = config.getInitParameter("charset");
System.out.println("过滤器名称:" + filterName);
System.out.println("字符集编码:" + charset);
}
}
使用过滤器拦截敏感字符
sensitive.jsp
<%--
Created by IntelliJ IDEA.
User: root
Date: 2021/9/15
Time: 14:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>过滤敏感字符</title>
</head>
<body>
<form action="sensitiveServlet" method="post">
留言:
<textarea cols="50" rows="10" name="msg"></textarea>
评论:
<textarea cols="50" rows="10" name="remark"></textarea>
<input type="submit" value="提交">
</form>
</body>
</html>
sensitive.txt
dfgrfhjh
hgffghmj,
yjuk
jy
filter.SensitiveWordsFilter.java
package filter;
import util.MyRequest;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@WebFilter(filterName = "sensitiveFilter", urlPatterns = {"/*"},
initParams = {
@WebInitParam(name = "encoding", value = "utf-8")
})
public class SensitiveWordsFilter implements Filter {
private List<String> list = new ArrayList<>();
public void init(FilterConfig filterConfig) throws ServletException {
//初始化,读取字符文件,存放到集合中
InputStream stream=filterConfig.getServletContext().getResourceAsStream("/WEB-INF/classes/sensitive.txt");
InputStreamReader is=null;
BufferedReader reader=null;
try {
is=new InputStreamReader(stream,"utf-8");
reader=new BufferedReader(is);
String txt="";
while ((txt=reader.readLine())!=null){
list.add(txt);
System.out.println(txt);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
reader.close();
is.close();
stream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
//3.创建代理对象,增强getParameter方法
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
request.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
MyRequest myRequest=new MyRequest(request,list);
filterChain.doFilter(myRequest,servletResponse);
}
@Override
public void destroy() {
}
}
servlet.SensitiveServlet.java
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/sensitiveServlet")
public class SensitiveServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String msg = req.getParameter("msg");
String remark = req.getParameter("remark");
System.out.println(msg);
System.out.println(remark);
out.print("留言内容:" + msg);
out.print("评论内容:" + remark);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
使用过滤器实现自动登录
login.jsp
<%--
Created by IntelliJ IDEA.
User: root
Date: 2021/9/15
Time: 9:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
${msg}
<form action="loginServlet" method="post">
用户名:<input name="userName" placeholder="UserName"/><br/>
密码:<input type="password" name="passWord" placeholder="passWord"/><br/>
<input type="checkbox" name="autoLogin"/>自动登录<br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
page.index1.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: root
Date: 2021/9/15
Time: 9:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
hello
<c:if test="${user != null}">
用户名:${user.getUserName()}
</c:if>
<c:if test="${user eq null}">
<a href="../login.jsp">请登录</a>
</c:if>
</body>
</html>
servlet.LoginServlet.java
package servlet;
import entity.User;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
try {
String userName = req.getParameter("userName");//获取用户名
String passWord = req.getParameter("passWord");//获取密码
User user = new User();
user.setUserName(userName);
user.setPassWord(passWord);
//调用业务层处理数据
UserService userService = new UserService();
User userLogin = userService.login(user);
if (userLogin == null) {
//登录失败
req.setAttribute("msg","登录失败");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}else{
//登录成功
//记住密码
String autoLogin = req.getParameter("autoLogin");
System.out.println("autoLogin="+autoLogin);
if ("on".equals(autoLogin)){
//选中自动登录
Cookie cookie=new Cookie("autoLogin",user.getUserName()+"#"+user.getPassWord());
cookie.setPath(req.getContextPath());
cookie.setMaxAge(20);
resp.addCookie(cookie);
}// 使用session记录用户信息
req.getSession().setAttribute("user", user);
resp.sendRedirect(req.getContextPath() + "/page/index1.jsp");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
filter.LoginFilter01.java
package filter;
import entity.User;
import service.UserService;
import util.CookieUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebFilter(filterName = "LoginFilter01",urlPatterns = {"/page/*"},
initParams = {
@WebInitParam(name = "encoding",value = "utf-8")
})
public class LoginFilter01 implements Filter {
String loginFilter;
String charset;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
loginFilter=filterConfig.getFilterName();
charset=filterConfig.getInitParameter("encoding");
System.out.println(loginFilter+"过滤器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(charset);
servletResponse.setCharacterEncoding(charset);
servletResponse.setContentType("text/html;charset=utf-8");
//判断session中石=是否存在有用的用户信息
HttpServletRequest req=(HttpServletRequest)servletRequest;
User user=(User) req.getSession().getAttribute("user");
if(user!=null){
//有用户信息 放行
filterChain.doFilter(req,servletResponse);
}else{
//session中没有用户信息 从cookie中获取
Cookie[] cookies=req.getCookies();
Cookie cookie= CookieUtils.findCookie(cookies,"autoLogin");
//查看cookie中是否有用户信息
if(cookie==null){
filterChain.doFilter(req,servletResponse);//放行
}else{
// 查到,将用户信息存入到session中,放行
String username = cookie.getValue().split("#")[0];
System.out.println(username);
String password = cookie.getValue().split("#")[1];
System.out.println(password);
User user1=new User();
user1.setUserName(username);
user1.setPassWord(password);
UserService userService=new UserService();
try{
User user2=userService.login(user1);
if(user2==null){
filterChain.doFilter(req,servletResponse);//放行
}else{
//将用户信息存入到session中 放行
req.getSession().setAttribute("user", user2);
filterChain.doFilter(req, servletResponse);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
@Override
public void destroy() {
System.out.println(loginFilter+"过滤器销毁!");
}
}