大数据必学Java基础(一百一十七):三个案例开发

举报
Lansonli 发表于 2022/12/23 13:52:38 2022/12/23
【摘要】 三个案例开发一、记录请求日志需求:记录每次请求中如下的信息并存储进入日志文件请求的来源浏览器所在电脑IP请求的资源 URL请求发生的时间监听器代码package com.lanson.listener;import javax.servlet.ServletRequest;import javax.servlet.ServletRequestEvent;import javax.servle...

三个案例开发

一、记录请求日志

需求:记录每次请求中如下的信息并存储进入日志文件

  • 请求的来源
  • 浏览器所在电脑IP
  • 请求的资源 URL
  • 请求发生的时间

监听器代码

package com.lanson.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
@WebListener
public class RequestLogListener implements ServletRequestListener {
    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 获得请求发出的IP
        // 获得请求的URL
        // 获得请求产生的时间
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        String remoteHost = request.getRemoteHost();
        String requestURL = request.getRequestURL().toString();
        String reqquestDate = simpleDateFormat.format(new Date());
        // 准备输出流
        try {
            PrintWriter pw =new PrintWriter(new FileOutputStream(new File("d:/lanson.txt"),true));
            pw.println(remoteHost+" "+requestURL+" "+reqquestDate );
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


二、统计实时在线人数

需求:

  • 当任何一个账户处于登录状态时,在线统计总数+1,离线时-1
  • 通过session监听器实现计数,但是在线人数要保存在Application域中

准备监听器

package com.lanson.listener;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
@WebListener
public class OnLineNumberListener implements HttpSessionListener  {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 向application域中 增加一个数字
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        Object attribute = application.getAttribute("count");
        if(null == attribute){// 第一次放数据
            application.setAttribute("count", 1);
        }else{
            int count =(int)attribute;
            application.setAttribute("count", ++count);
        }
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 向application域中 减少一个数字
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        int count =(int)application.getAttribute("count");
        application.setAttribute("count", --count);
    }
}

准备销毁监听的servlet

package com.lanson.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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
@WebServlet(urlPatterns = "/logout.do")
public class Logout extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title%sSourceCode%lt;/title>
  </head>
  <body>
  当前在线人数为:${applicationScope.count}
  </body>
</html>

分别用不同的客户端访问index.jsp 和logout.do测试即可

三、项目重启免登录

Session序列化和反序列化

1、序列化与反序列

把对象转化为字节序列的过程称为序列化(保存到硬盘,持久化)

把字节序列转化为对象的过程称为反序列化(存放于内存)

2、序列化的用途

把对象的字节序列永久保存到硬盘上,通常放到一个文件中。

把网络传输的对象通过字节序列化,方便传输本节作业

3、实现步骤

要想实现序列化和反序列化需要手动配置

3.1、新建文件如图所示:

3.2、Context.xml中文件如下

<?xml version="1.0" encoding="UTF-8"?>

  <Context>

       <Manager className="org.apache.catalina.session.PersistentManager">

         <Store className="org.apache.catalina.session.FileStore" directory="d:/session"/>

      </Manager>

  </Context>

3.3、注意实体类必须实现serializable接口

4、开发过程

4.1、准备实体类

package com.lanson.pojo;
import java.io.Serializable;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
public class User  implements Serializable {
    private String username;
    private String pwd;

4.2、开发登录信息输入页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title%sSourceCode%lt;/title>
  </head>
  <body>
  <form action="loginController.do" method="post">
    用户名:<input type="text" name="user"> <br/>
    密码:<input type="password" name="pwd"><br/>
    <input type="submit" value="提交">
  </form>
  </body>
</html>

4.3、开发登录信息验证Servlet

package com.lanson.controller;
import com.lanson.listener.MySessionActivationListener;
import com.lanson.pojo.User;
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;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
@WebServlet("/loginController.do")
public class LoginController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("user");
        String pwd = req.getParameter("pwd");
        // user
        User user =new User(username,pwd);
        // session
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
    }
}

4.4、开发校验当前是否已经登录的Controller

package com.lanson.controller;
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;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
@WebServlet(urlPatterns = "/loginCheckController.do")
public class LoginCheckController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 判断是否登录
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        Object listener = session.getAttribute("listener");// 获得对应的监听器
        String message ="";
        if(null != user){
            message="您已经登录过";
        }else{
            message="您还未登录";
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println(message);
    }
}

4.5、测试,先登录

然后请求loginCheckController.do 校验是否登录过,然后重启项目,再起请求loginCheckController.do 校验是否登录过,发现重启后,仍然是登录过的。

4.6、监听钝化和活化

准备监听器

package com.lanson.listener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;
/**
 * @Author: Lansonli
 * @Description: MircoMessage:Mark_7001
 */
public class MySessionActivationListener implements HttpSessionActivationListener, Serializable {
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        System.out.println(se.getSession().hashCode()+"即将钝化");
    }
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println(se.getSession().hashCode()+"已经活化");
    }
}

登录时绑定监听器

@WebServlet("/loginController.do")
public class LoginController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("user");
        String pwd = req.getParameter("pwd");
        // user
        User user =new User(username,pwd);
        // session
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        // 绑定监听器
        session.setAttribute("listener", new MySessionActivationListener());
    }
}

重启项目,重复测试即可。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。