Java Web学习总结(八) Filter和Litener
1.Filter
1.什么是Filter
过滤器, 对Servlet容器调用Servlet的过程进行拦截.拦截Servlet请求, 拦截Servlet响应.
init(FileConfig filterConfig): 初始化过滤器
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
request: 对应于HttpRequest
response: 对应于HttpResponse
chain: 代表当前Filter链的对象
destory(): 释放Filter对象
2.Filter映射
映射规则基本与Servlet一致,有些不同如下:
-
映射配置
<filter> <filter-name>filtername</filter-name> <filter-class>filter完整类名(包括包名等..)</filter-class> </filter> <filter-mapping> <filter-name>filtername</filter-name> <url-pattern>映射地址(/某一filter | 使用通配符方式)</url-pattern> </filter-mapping>
-
针对具体请求方式拦截
<filter-mapping>
元素中有一个特殊的子元素<dispatcher>
, 有如下4个值:值 描述 REQUEST 用户直接访问时才会被拦截 INCLUDE 拦截通过RequestDispatcher.include()方式访问 FORWARD 拦截通过RequestDispatcher.forward()方式访问 ERROR 拦截通过声明式异常处理机制调用的
3.Filter链
如果有多个Filter对同一URL进行拦截, 那么它们之间就形成Filter链
4.FilterConfig 接口
用以获取Filter程序在web.xml文件中的配置信息
方法 | 描述 |
---|---|
getFilterName() | <filter-name> 的值 |
getInitParameter(String name) | 返回web.xml指定名称的初始化参数的值 |
Enumeration getInitParemeterNames() | 返回所有Filter设置的所有初始化参数名称 |
ServletContext getServletContext() | 返回ServletContext 对象的引用 |
5.[案例]使用Filter实现自动登陆
-
User类
package ink.heat.entity; public class User { private String username; private String password; public User() { } public User(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
-
登陆页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="loginServlet" method="POST"> 用户名:<input type="text" name="username"/><br/> 密码: <input type="password" name="password"/><br/> 自动登陆: <input type="radio" value="1" name="isAutoLogin"/> <input type="submit" value="登陆"> </form> </body> </html>
-
首页
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登陆用户信息</title> </head> <body> <center> <h3>欢迎光临</h3> </center> <c:choose> <c:when test="${sessionScope.user == null}"> <a href="login.jsp">用户登陆</a> </c:when> <c:otherwise> 欢迎你, ${sessionScope.user.username}! <a href="loginoutServlet">用户注销</a> </c:otherwise> </c:choose> </body> </html>
-
LoginServlet
package ink.heat.Servlet; import java.io.IOException; 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 javax.servlet.http.HttpSession; import ink.heat.entity.User; /** * Servlet implementation class LoginServlet */ @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.拿到用户名和密码 String username = (String)request.getParameter("username"); String password = (String)request.getParameter("password"); boolean isAutoLogin = false; System.out.println(username + "-" + password); Integer tag = (Integer)request.getAttribute("isAutoLogin"); if (tag != null) { isAutoLogin = true; } //2.对用户名和密码进行校验 if ("zs".equals(username) && "123".equals(password)) { //校验成功:将user对象存入session域中 User user = new User(username, password); HttpSession session = request.getSession(); session.setAttribute("user", user); //如果是用户勾选自动登陆,则将用户信息放入Cookie中 Cookie[] cookies = null; if (isAutoLogin) { cookies[0] = new Cookie("autologin", username + "/" + password); for (Cookie cookie:cookies) { cookie.setMaxAge(60 * 60); cookie.setPath(request.getContextPath()); response.addCookie(cookie); } } //跳转至首页 response.sendRedirect("index.jsp"); } else { //校验失败:返回错误信息errMsg,跳转至登陆页 request.setAttribute("errMsg", "用户名或密码错误!"); request.getRequestDispatcher("login.jsp").forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
-
LoginoutServlet
package ink.heat.Servlet; import java.io.IOException; 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; /** * Servlet implementation class LoginOutServlet */ @WebServlet("/loginoutServlet") public class LoginoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginoutServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //用户注销 request.getSession().removeAttribute("user"); //删除Cookie Cookie cookie = new Cookie("autologin", "msg"); cookie.setPath(request.getContentType()); cookie.setMaxAge(0); response.setCharacterEncoding("utf-8"); response.getWriter().print("注销成功"); response.sendRedirect("index.jsp"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }