监听器的使用,jspl标签库通过登录验证打印表格

127 阅读2分钟

一、监听器

作为了解内容:

监听器为三种,最大的监听器为 Application监听器,这里就已application监听器为例做一个例题,另外两个监听器参照下标使用方法都是一样的

servlet中的监听器.png

二、jspl 标签库

下载

这是一个外部jar包,需要引入,作用在方便在jsp中书写 前端代码,一个标签库

下载地址:search.maven.org/search?q=js…

下载之后需要导报,注意一定要方法WEB-INF的lib文件夹下面,否则报错

导入方法

<%--常用if else for标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--数字、日期转换--%>
<%@taglib prefix="ftm" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--方法标签--%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

主要用到的标签为:c 标签, 字符串和日期转换的标签 ftm 标签,还有一个方法标签 fn

三、监听器获取访问路径

问题:如果页面访问的是双层路径:/login/user,转发可能出现结果为:/login/login/user

解决办法:

  1. 固定项目名写法: /项目名/login/user
  2. 使用pageContext.request.contextPath相当于是项目名,{pageContext.request.contextPath} 相当于是项目名, 即{pageContext.request.contextPath}/login/user
  3. 使用监听器,如下代码通过监听器即可获取项目的路径
@WebListener
public class Listen implements ServletContextListener {
    public  void contextInitialized(ServletContextEvent sce) {
        ServletContext app = sce.getServletContext();
        String pname = app.getContextPath();
        app.setAttribute("pname",pname);
        System.out.println("服务器启动");
        System.out.println("项目启动路径"+pname);
    }
​
    public  void contextDestroyed(ServletContextEvent sce) {
        System.out.println("服务器停止");
​
    }
}

那么在获项目路径的时候就可以调用我们自己写的监听器来获取路径了

${pname}/login/user

四、综合练习,使用标签库打印表格

要求:用户登录后点击查询,可以查询所有商品信息,商品信息需要以表格形式展示

运行结果:

Servlet简单应用.gif 代码:

  • 编写application监听器
@WebListener
public class Listen implements ServletContextListener {
    public  void contextInitialized(ServletContextEvent sce) {
        ServletContext app = sce.getServletContext();
        String pname = app.getContextPath();
        app.setAttribute("pname",pname);
        System.out.println("服务器启动");
        System.out.println("项目启动路径"+pname);
    }
​
    public  void contextDestroyed(ServletContextEvent sce) {
        System.out.println("服务器停止");
​
    }
}
  • 编写product对象
package com.zking.entity;
​
public class Product {
    private int id;
    private String name;
    private double price;
    private int count;
    private  String date;
​
    public Product() {
    }
​
    public Product(int id, String name, double price, int count, String date) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.count = count;
        this.date = date;
    }
​
    public int getId() {
        return id;
    }
​
    public void setId(int id) {
        this.id = id;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public double getPrice() {
        return price;
    }
​
    public void setPrice(double price) {
        this.price = price;
    }
​
    public int getCount() {
        return count;
    }
​
    public void setCount(int count) {
        this.count = count;
    }
​
    public String getDate() {
        return date;
    }
​
    public void setDate(String date) {
        this.date = date;
    }
​
    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", price=" + price +
                ", count=" + count +
                ", date='" + date + ''' +
                '}';
    }
}
  • 编写login服务器
package com.zking.user;
​
import com.zking.entity.Product;
​
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
​
@WebServlet("/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        user的操作事件
        String operate = req.getParameter("operate");
        switch (operate) {
            case "login" :login(req,resp);break;
            case "logout" :logout(req,resp);break;
            case "find" :find(req,resp);break;
        }
    }
​
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("登录成功");
        req.getSession().setAttribute("user","admin");
        resp.sendRedirect("login.jsp");
    }
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("注销成功");
//        req.getSession().removeAttribute("user");
        req.getSession().invalidate();
        resp.sendRedirect("login.jsp");
    }
    private void find(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("查找成功");
        ArrayList<Product> arrayList = new ArrayList<Product>();
        arrayList.add(new Product(1,"斐乐鞋子",300,100,"2022-9-24"));
        arrayList.add(new Product(2,"adidas",320,80,"2022-9-26"));
        arrayList.add(new Product(3,"nike",400,200,"2022-9-25"));
        arrayList.add(new Product(4,"冠军",230,30,"2022-4-21"));
        req.getSession().setAttribute("Product",arrayList); //转发
        resp.sendRedirect("login.jsp");
    }
}
​
  • 编写login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--常用if else for标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--数字、日期转换--%>
<%@taglib prefix="ftm" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>test</title>
</head>
<body>
    <h3>登录状态 ${empty user ? "未登录":"已登录"}</h3>
​
    <a href="login?operate=login">登录</a>
    <a href="login?operate=logout">注销</a>
    <br>
    <a href="login?operate=find">查找</a>
    ${msg}
<%--判断是否登录--%>
    <c:if test="${user==null}">
        未登录: 你好游客!
    </c:if>
​
    <c:if test="${user!=null}">
        欢迎使用!
        <table cellspacing="0"border="1">
            <tr>
                <th>序号</th>
                <th>名称</th>
                <th>价格</th>
                <th>数量</th>
                <th>日期</th>
            </tr>
            <c:forEach items="${Product}" var="p" varStatus="i">
            <tr>
                    <td>${p.getId()} 当前索引为:${i.index} </td>
                    <td>${p.name}</td>
                    <td>${p.price}</td>
                    <td>${p.count}</td>
                    <td>
                        <ftm:parseDate value="${p.date}" var="p" pattern="yyyy-MM-dd"></ftm:parseDate>
                        <ftm:formatDate value="${p}" pattern="yyyy年MM月dd日"></ftm:formatDate>
                    </td>
            </tr>
            </c:forEach>
        </table>
    </c:if>
</body>
</html>

四、总结

  1. 监听器在使用的时候,需要声明:@WebListener,三种类型的监听器,对应的调用方法大同小异

  2. 使用jspl标签库的使用一定要调用正确方法,比如字符串和日期的转换,调用的是ftm ,转换的时候,date日期传入时为字符串,所以要通过parseDate转换成日期格式,再将日期格式转换成我们想要看到的日期结果

  3. 补充

    3.1 EL表达式获取数据的顺序

    页面取值顺序:pageScope-->requestScope-->sessionScope-->applicationScope