在之前作业项目的基础上,编写过滤器和监听器:
过滤器:实现拦截访问主页的请求,只有用户登录成功了才能访问主页
监听器:统计所有用户登录的次数
package com.qiku.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "loginFilter",urlPatterns = "/index.*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 只有登录成功之后,才能访问主页
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
// 获取请求路径
String servletPath = request.getServletPath();
if (user==null && !servletPath.contains("login")){
// 用户没登录 且 不是登录请求 则 转发到登录页面
RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
requestDispatcher.forward(servletRequest,servletResponse);
}else {
// 表示登录成功 或者 是登录请求
filterChain.doFilter(servletRequest,servletResponse);
}
}
}
package com.qiku.listener;
import com.qiku.entity.User;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;
import java.util.Map;
@WebListener
public class UserLoginListener implements HttpSessionAttributeListener, ServletContextListener {
/**
* 统计所有用户的登录次数
* 在ServletContext中 声明一个属性userMap 保存 Map<String,,Integer></>
* 监听 session中 属性名为 user 的变化
* @param sce
*/
private ServletContext servletContext=null;
@Override
public void contextInitialized(ServletContextEvent sce) {
servletContext=sce.getServletContext();
Map<String,Integer> userMap=new HashMap<>();
servletContext.setAttribute("userMap",userMap);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
servletContext=null;
}
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("新增了属性..."+se.getName());
checkUserLogin(se);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("删除了属性:"+se.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println("修改了属性:"+se.getName()+"="+se.getValue());
checkUserLogin(se);
}
public void checkUserLogin(HttpSessionBindingEvent se){
if (se.getName().equals("user")){
System.out.println("有新用户登录了....");
// 获取用户名
HttpSession session = se.getSession();
User user = (User) session.getAttribute("user");
String username = user.getUsername();
// 从ServletContext中获取map
Map<String ,Integer> userMap = (Map) servletContext.getAttribute("userMap");
//判断userMap中是否有key 包含 username
if (userMap.get(username)==null || userMap.get(username)==0){
//不包含 说明第一次登录
userMap.put(username,1);
}else {
//说明 不是第一次登录 将登录次数 +1即可
userMap.put(username,userMap.get(username)+1);
}
}
}
}
<%--
Created by IntelliJ IDEA.
User: 86136
Date: 2022/5/19
Time: 10:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>统计用户登录的次数</title>
</head>
<body>
<h1>所有用户的登录信息如下:</h1>
${userMap}
</body>
</html>
package com.qiku.servlet;
import com.qiku.entity.User;
import com.qiku.service.UserService;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
// 1 获取请求中的用户名和密码
String username=req.getParameter("username");
String password=req.getParameter("password");
System.out.println("用户名:"+username+",密码:"+password);
// 2 创建Service对象 实现数据的封装校验功能
UserService userService=new UserService();
// 将username和password封装成一个user对象,交给userService去实现登录逻辑
User user=userService.login(new User(username,password));
// 3 根据结果转发页面
if (user==null){
System.out.println("登录失败,用户名或者密码错误");
req.setAttribute("error","登录失败,用户名或者密码错误");
// 获取转发器
RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
requestDispatcher.forward(req,resp);//转发
} else {
System.out.println("登录成功...");
// 将登录成功的用户 存入session中 实现多个请求共享
HttpSession session = req.getSession();
session.setAttribute("user",user);
// 重定向到主页
resp.setContentType("text/html;charset=utf-8");
resp.sendRedirect("index.jsp");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}