title: 【学习之路】Filter过滤器
draft: true
tags:
- 学习之路
- JavaEE
- Filter
categories: - JavaEE
- Filter
description: ‘Filter学习,理解什么是Filter过滤器和Filter的作用’
date: 2020-10-27 19:50:22
cover:
什么是Filter过滤器
- Filter过滤器它是JavaWeb的三大组件之一。三大组件分别是Servlet程序、Listener监听器、Filter过滤器
- Filter过滤器它是JavaEE的规范。就是接口
- Filter过滤器作用是:拦截请求,过滤响应
如何使用Filter
- 编写一个类去实现Filter借口
- 实现过滤方法
doFilter()
- 到web.xml中去配置Filter的拦截路径
- Filter代码
public class TestFilter implements Filter{
//doFilter 方法专门拦截请求,可以做权限检查
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletRequest hsr = (HttpServletRequest) servletRequest;
HttpSession session = hsr..getSession();
Object user = session.getAttribute("user");
//如果等于null,说明还没有登录
if (user == null){
servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
return;
}else{
//让程序继续往下访问目标资源
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
- web.xml代码
<filter>
<filter-name>TestFilter</filter-name>
<filter-class>com.test.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
- loginServlet程序
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
resp.setContentType("text/html; charset=UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("zhangsan".equals(username) && "123456".equals(password)) {
req.getSession().setAttribute("user",username);
resp.getWriter().write("登录 成功!!!");
} else {
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
}
- login.jsp页面
<form action="http://localhost:8080/15_filter/loginServlet" method="post">
用户名:<input type="text" name="username"/> <br>
密 码:<input type="password" name="password"/> <br>
<input type="submit" />
</form>
Filter的生命周期
在web工程启动的时候执行
- 构造器方法
- init初始化方法
每次拦截到请求都会执行
- doFilter过滤方法
停止web工程就会执行
- destroy销毁