使用过滤器和监听器制作一个简单的用户登录并且显示登录用户的例子
登录功能servlet
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); //任何人都可以登录成功 //关键: 保存登录标记到session里面 request.getSession().setAttribute("ip", request.getRemoteHost()); request.getSession().setAttribute("loginInfo", name); response.sendRedirect(request.getContextPath()+"/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注销功能servlet
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //如果在session中不为空的话,进行删除 if(session != null){ session.removeAttribute("loginInfo"); response.sendRedirect(request.getContextPath() + "/index.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
pojo类,用户实体类
public class LoginUser { private String id; //用户特有的id private String name; //用户的姓名 private String date; //用户登录的时间 private String ip; //用户登录的ip public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public LoginUser(String id, String name, String date, String ip) { super(); this.id = id; this.name = name; this.date = date; this.ip = ip; } public LoginUser(){} }
监听器
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class LoginListener implements HttpSessionAttributeListener { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void attributeAdded(HttpSessionBindingEvent se) { //首先得到登录的用户名字 String name = se.getName(); if("loginInfo".equals(name)){ //在把登录的用户封装成为一个对象,并保存在list中 HttpSession session = se.getSession(); String username = (String) session.getAttribute(name); String date = sdf.format(new Date()); String id = session.getId(); String ip = (String) session.getAttribute("ip"); LoginUser user = new LoginUser(id, username, date, ip); //然后放进去list中 List<LoginUser> list =(List<LoginUser>)session.getServletContext().getAttribute("loginUsers"); ; if(list == null){ list = new ArrayList<LoginUser>(); } list.add(user); //放在context中显示 session.getServletContext().setAttribute("loginUsers", list); } } public void attributeRemoved(HttpSessionBindingEvent se) { //得到退出登录的用户先 String name = se.getName(); if("loginInfo".equals(name)){ //要删除session中的用户,先得到session中数据 HttpSession session = se.getSession(); List<LoginUser> lists = (List<LoginUser>) session.getServletContext().getAttribute("loginUsers"); //得到在session中每个用户特定的id属性,进行删除 String id = session.getId(); for(LoginUser user : lists){ if(user.getId().equals(id)){ lists.remove(user); break; } } //然后在全局中再次刷新 session.getServletContext().setAttribute("loginUsers", lists); } } public void attributeReplaced(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } }
过滤器
import java.io.IOException; 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.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * 过滤器首先要实现javax.servlet的Filter接口,并且实现其中的方法 * @author Mao * */ public class demo1 implements Filter{ //过滤器的销毁方法 public void destroy() { System.out.println("过滤销毁"); } //过滤器的主方法 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; request.setCharacterEncoding("utf-8"); //过滤的开始拦截 System.out.println("请求的拦截 "); //使用装饰者的类进行加强,可以进行方法加强的过滤 MyServlet myrequest = new MyServlet(request); //放行,执行过滤完了以后的后面的逻辑,或者是执行过滤链中的其他过滤 chain.doFilter(myrequest,resp); //过滤后的执行 System.out.println("响应的拦截"); } //过滤器的初始化 public void init(FilterConfig config) throws ServletException { //通过FilterConfig的对象可以得到在web.xml中对过滤器的配置属性 String encoding = config.getInitParameter("encoding"); System.out.println(encoding); System.out.println("过滤的初始化"); } } /** * 当要对一个类中的方法进行改造和加强,可以使用装饰者模式 */ class MyServlet extends HttpServletRequestWrapper{ //1)要设置一个成员变量用来进行设置 private HttpServletRequest request; public MyServlet(HttpServletRequest request) { super(request); //2)在有参的构造方法中进行对成员变量的设置 this.request = request; } //3)重写要进行加强的方法 @Override public String getParameter(String name) { try { //1)得到原来的实际参数内容 String value = request.getParameter(name);//iso-8859-1 //2)增强 if(value!=null && "GET".equals(request.getMethod())){ value = new String(value.getBytes("iso-8859-1"),"utf-8"); } //3)返回增强后内容 return value; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public String[] getParameterValues(String name) { try { String[] values = request.getParameterValues(name); if(values!=null && "GET".equals(request.getMethod())){ for(int i=0;i<values.length;i++){ values[i] = new String(values[i].getBytes("iso-8859-1"),"utf-8"); } } return values; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } }
然后是在web.xml中各个配置
<filter> <filter-name>demo1</filter-name> <filter-class>a_example.demo1filter</filter-class> </filter> <filter-mapping> <filter-name>demo1</filter-name> <url-pattern>/demo1</url-pattern> </filter-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>d_listener_example.LogoutServlet</servlet-class> </servlet>
然后在页面上显示数据
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录用户</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="<c:url value='/LoginServlet'/>" method="post"> 用户名:<input type="text" name="name"/><br/> <input type="submit" value="登录"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>title</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 网站主页<hr/> <c:choose> <c:when test="${empty loginInfo }"> 请先<a href="<c:url value='/login.jsp'/>">登录</a> </c:when> <c:otherwise> 欢迎回来,你的用户名是:${loginInfo }, <a href="<c:url value='/LogoutServlet'/>">退出登录</a> </c:otherwise> </c:choose> <hr/> 当前网站的登录用户如下:<br/> <c:if test="${!empty loginUsers }"> <c:forEach items="${loginUsers}" var="user"> ${user.name } ${user.date } ${user.ip }<br/> </c:forEach> </c:if> </body> </html>
通过这个小例子,能够很好的去了解过滤器和监听器的总和运用