编程语言
首页 > 编程语言> > 重温Java Web的技术细节

重温Java Web的技术细节

作者:互联网

目录

一、背景


二、请求与响应

2.1、Http请求

/** 
* Servlet处理HTTP GET/POST请求
*/
public class HttpServletDemo extends HttpServlet {
	
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
	   ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp {
		...
    }
 }
## GET和POST请求的区别

# GET请求
GET /books/?name=computer&num=1 HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
# 注意最后一行是空行

# POST请求
POST /books/add HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
# 以下是POST请求Body
name=computer&num=1
/**
* HttpServlet类Service方法
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
      	
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }
    }
  • 对于Http Request请求,我们还需要理解幂等的概念:对同一个系统,使用同样的条件,一次请求和重复的多次请求对系统资源的影响是一致的。
  • 根据以上定义,我们认为GET请求一般情况下是幂等的(GET请求不会引起服务资源的变更),而POST请求是非幂等的(POST请求会提交数据并造成数据更改,造成不可逆,比如多次POST提交订单数据)。
API 备注
request.getParameter("参数名") 根据参数名获取参数值(注意,只能获取一个值的参数)
request.getParameterValue("参数名“) 根据参数名获取参数值(可以获取多个值的参数)
request.getMethod 获取Http请求方式
request.getHeader("User-Agent") 获取用台浏览器信息
request.getCookies 获取与请求相关的Cookies
request.getSession 获取与用户相关的会话
... ...

2.2、Http响应

protected void doGet(HttpServletRequest req, HttpServletResponse resp){
		// 这是一个字节流
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-disposition", "attachment;filename=" + filename);

        InputStream fis = this.getClass().getResourceAsStream("download.xlsx");
        OutputStream os = resp.getOutputStream();
        byte[] bis = new byte[1024];
        while (-1 != fis.read(bis)) {
            os.write(bis);
        }
}
//设置refresh响应头控制浏览器每隔1秒钟刷新一次
response.setHeader("refresh", "1");

//可分别通过三种方式禁止缓存当前文档内容
response.setDateHeader("expries", -1);

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Pragma", "no-cache")

// 重定向:收到客户端请求后,通知客户端去访问另外一个web资源
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
     // 通过sendRedirect方法实现请求重定向
     resp.sendRedirect(req.getContextPath() + "/welcome.jsp");
}
// 请求分派
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
  req.getRequestDispatcher("/result.jsp").forward(req,resp);
}
代码 消息 描述
200 OK 请求成功。
401 Unauthorized 所请求的页面需要授权
404 Not Found 服务器无法找到所请求的页面。
500 Internal Server Error 未完成的请求。服务器遇到了一个意外的情况
... ... ...
// 返回HTTP 500状态码
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
  resp.sendError(500);
}

在这里插入图片描述


三、ServletConfig

3.1 测试ServletConfig参数

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
	<servlet>
         <servlet-name>http-demo</servlet-name>
         <servlet-class>demo.servlet.HttpServletDemo</servlet-class>
		  <!-- 设置该servlet的管理员邮箱地址 -->
          <init-param>
              <param-name>adminEmail</param-name>
              <param-value>admin@163.com</param-value>
          </init-param>
     </servlet>
</web-app>
		
public class HttpServletDemo extends HttpServlet {

    // 重写Get请求方法,返回一个表单页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("GBK");
        PrintWriter out =resp.getWriter();
        out.println("<html><body>");
        out.println("管理员邮箱:");
        out.println(getServletConfig().getInitParameter("adminEmail"));
        out.println("<br>");
        out.println("</body></html>");
    }
}

在这里插入图片描述


四、ServletContext

-web应用同样也需要一些初始化的参数,但 相对于每一个Servlet有一个ServletConfig来说,一个Web应用(确切的说是每个JVM)仅有一个ServletContext来存放这些参数,这个ServletContext对Web应用中的每个Servlet都可用。
在这里插入图片描述

4.1 测试ServletContext参数

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
         
		<!-- 设置web应用的统一标题栏 -->
        <context-param>
            <param-name>title</param-name>
            <param-value>My-App网站</param-value>
        </context-param>

        <servlet>
            <servlet-name>http-demo</servlet-name>
            <servlet-class>demo.servlet.HttpServletDemo</servlet-class>

            <init-param>
                <param-name>adminEmail</param-name>
                <param-value>admin@163.com</param-value>
            </init-param>
        </servlet>

        <servlet-mapping>
            <servlet-name>http-demo</servlet-name>
            <url-pattern>/http-demo</url-pattern>
        </servlet-mapping>
</web-app>
public class HttpServletDemo extends HttpServlet {

    // 重写Get请求方法,返回一个表单页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        resp.setContentType("text/html");
        resp.setCharacterEncoding("GBK");
        PrintWriter out =resp.getWriter();
        out.println("<html><body>");
        out.println("<title>"+getServletContext().getInitParameter("title")+"</title>");
        out.println("管理员邮箱:");
        out.println(getServletConfig().getInitParameter("adminEmail"));
        out.println("<br>");
        out.println("</body></html>");
    }
 }

在这里插入图片描述

// 在web应用中,以下两句代码等价
getServletContext().getInitParameter("title");
getServletConfig().getServletContext().getInitParameter("title");

4.2、ServletContext属性

// 重写Post请求方法,提交表单上的数据,并返回结果页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer age = Integer.parseInt(req.getParameter("age"));
        if (name != null && age != null) {
            User user = new User(name, age);
            req.setAttribute("name", name);
            req.setAttribute("age", age);
            // 设置提交成功次数属性,并同步加锁,防止多线程并发异常
            synchronized (getServletContext()) {
                if (user.checkName()) {
                    Long postCount = getServletContext().getAttribute("postCount") == null ? 1L
                            : Long.parseLong(getServletContext().getAttribute("postCount").toString()) + 1L;
                    getServletContext().setAttribute("postCount", postCount);

                    req.setAttribute("result", "登记成功" + "! 总共已有" + postCount + "人数登记!!");
                } else {
                    req.setAttribute("result", "登记失败:名称中包含非法字符");
                }
            }
            RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
            view.forward(req, resp);

        }

    }

在这里插入图片描述
在这里插入图片描述

属性 参数
设置方法 setAttribute(String name,Object value) 只能在web.xml中设置
返回类型 Object String
获取方法 getAttribute(String name). getInitParameter(String s)

五、属性的作用域

属性作用域 备注
ServletContext web应用存活期间都可以设置并使用属性;应用关闭上下文撤消后相应属性也会消失 各个Servlet都可以使用,但线程不安全,一般适在于常量属性等,比如数据库连接
HttpSession HttpSession应用存活期间都可以设置并使用属性;会话超时或被人为撤消后相应属性也会消失 与会话相关的都可以使用,比如电商网站的购物车属性
HttpServletRequest 每次请求生成时可设置或使用属性,直到这个请求在service方法中消失 请求中属性是线程安全的,类似于局部变量

六、HttpSession

  1. 客户端在第一次请求时没有携带任何sessionId,服务端Servlet容器就会给客户端创建一个HttpSession对象 存储在服务器端,然后给这个对象创建一个sessionID 作为唯一标识。同时
    这个sessionID还会放在一个cookie里,通过response返回客户端。
  2. 客户端第二次发出请求,cookie中会携带sessionId,servlet容器拿着这个sessionID在服务器端查找对应的HttpSession对象,找到后就直接拿出来使用。
  3. Servlet会为不同的客户端创建不同的sessionId及session对象,代表不同的状态。

在这里插入图片描述

6.1 HttpSession的关键方法

方法 描述
getSession() 获取Session 对象
setAttribute() 在Session 对象中设置属性
getAttribute() 在Session 对象中获取属性
removeAttribute() 在Session 对象中删除属性
invalidate() 使Session 对象失效
setMaxInactiveInterval() 设置Session 对象最大间隔时间(在这段时间内,客户端未对这个会话有新的请求操作,该会话就会撤消)

6.2 简易的购物车使用HttpSession

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <context-param>
        <param-name>title</param-name>
        <param-value>购物网站</param-value>
    </context-param>

    <!-- 网站session失效时间为30分钟 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <!-- 登录servlet -->
    <servlet>
        <servlet-name>http-demo</servlet-name>
        <servlet-class>demo.servlet.HttpServletDemo</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>http-demo</servlet-name>
        <url-pattern>/http-demo</url-pattern>
    </servlet-mapping>

    <!-- 购物车servlet -->
    <servlet>
        <servlet-name>cart</servlet-name>
        <servlet-class>demo.servlet.CartServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cart</servlet-name>
        <url-pattern>/cart</url-pattern>
    </servlet-mapping>

</web-app>
/**
 * 购物网站登录页面
 *
 * @author zhuhuix
 * @date 2020-08-28
 */
public class HttpServletDemo extends HttpServlet {
    //static int i=0 ;

    // 重写Get请求方法,返回登录表单页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重写Post请求方法,进行登录,登录成功后跳车购物车页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            req.getSession().setAttribute("name",name);
            RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
            view.forward(req, resp);
        }
    }
}
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}用户登录</title>
</head>
<body>
<div class="container">

    <form role="form" method="post" action="http-demo" class="form-horizontal">
        <div class="form-group">
            <h4 class="col-sm-3 col-sm-offset-3">用户登录</h4>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">用户名</label>
            <div class="col-sm-3">
                <input name="name" type="text" class="form-control" placeholder="请输入用户名">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">密码</label>
            <div class="col-sm-3">
                <input name="password" type="password" class="form-control" placeholder="请输入密码">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-3 col-sm-offset-3">
                <button class="btn btn-primary">点击登录</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

在这里插入图片描述

<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}购物车</title>
</head>
<body>
<div class="container">

    <form role="form" method="post" action="cart" class="form-horizontal">
        <div class="form-group">
            <h4 class="col-sm-3 col-sm-offset-1">${name}的购物车</h4>
        </div>
        <table class="table table-bordered table-condensed" style="width: 30%">
            <thead>
            <tr>
                <td>货物</td>
                <td>数量</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>手机</td>
                <td><input type="number" name="phoneNumber" value=${phoneNumber}> </td>
            </tr>
            <tr>
                <td>电脑</td>
                <td><input type="number" name="pcNumber" value=${pcNumber}> </td>
            </tr>
            <tr>
                <td>书本</td>
                <td><input type="number" name="bookNumber" value=${bookNumber}> </td>
            </tr>
            </tbody>
        </table>

        <div class="form-group">
            <div class="col-sm-1 col-sm-offset-1">
                <button class="btn btn-primary">点击提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

在这里插入图片描述

/**
 * 购物车Servlet
 *
 * @author zhuhuix
 * @date 2020-08-29
 */
public class CartServlet extends javax.servlet.http.HttpServlet {


    // 重写Post请求方法,提交购物车的数据,并返回结果页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查找页面上的购物数量,并放入session中

        req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
        req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
        req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));

        RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
        view.forward(req, resp);
    }
}
<!--结果页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}购物结果</title>
</head>
<body>
<div class="container">

    <div class="row">
        <h3 class="col-sm-3 col-sm-offset-1">${name}的购物结果</h3>
    </div>
    <table class="table table-bordered table-condensed" style="width: 30%">
        <thead>
        <tr>
            <td>已购货物</td>
            <td>已购数量</td>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>手机</td>
            <td>${phoneNumber} </td>
        </tr>
        <tr>
            <td>电脑</td>
            <td>${pcNumber}</td>
        </tr>
        <tr>
            <td>书本</td>
            <td>${bookNumber} </td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>

在这里插入图片描述

  1. 用户登录网站后在购物车页面提交购物结果:
    在这里插入图片描述
  2. 用户退出网站,重新登录 后进入购物车页面,网站后台将HttpSession中的数据重新调取到页面进行显示:
    在这里插入图片描述
    在这里插入图片描述
  <!-- 网站session失效时间为1分钟 -->
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

在这里插入图片描述


七、监听器

7.1 监听器测试--在线会话数统计

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

        <context-param>
            <param-name>title</param-name>
            <param-value>My-App网站</param-value>
        </context-param>

        <!-- 监听者 负责监听HttpSession创建与销毁-->
        <listener>
            <listener-class>demo.servlet.HttpSessionListenerDemo</listener-class>
        </listener>

        <!-- 登录servlet -->
        <servlet>
            <servlet-name>http-demo</servlet-name>
            <servlet-class>demo.servlet.HttpServletDemo</servlet-class>

            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>http-demo</servlet-name>
            <url-pattern>/http-demo</url-pattern>
        </servlet-mapping>
    
</web-app>
/**
 * HttpSession监听器测试:统计当前服务器在线人数
 */
public class HttpSessionListenerDemo implements javax.servlet.http.HttpSessionListener {
    @Override
    public void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
        SessionStatics.increase();
    }

    @Override
    public void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
        SessionStatics.decrease();
    }
}

/**
 * 计数类
 */
public  class SessionStatics {
    private  static volatile Long count=0L;

    public static void increase(){
        synchronized (SessionStatics.class) {
            count++;
        }
    }

    public static void decrease(){
        synchronized (SessionStatics.class) {
            count--;
        }
    }

    public static Long getCount(){
        return count;
    }
}
/**
 * HttpServlet模拟一个登录页面
 *
 * @author zhuhuix
 * @date 2020-08-28
 */
public class HttpServletDemo extends HttpServlet {

    // 重写Get请求方法,返回一个表单页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重写Post请求方法,提交表单上的数据,并返回结果页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            // checkUserAndPassword
            req.setAttribute("name", name);

            req.setAttribute("result","登录成功,当前在线人数:"+SessionStatics.getCount());

            RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
            view.forward(req, resp);
        }
    }
}
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}用户登录</title>
</head>
<body>
<div class="container">

    <form role="form" method="post" action="http-demo" class="form-horizontal">
        <div class="form-group">
            <h4 class="col-sm-3 col-sm-offset-3">用户登录</h4>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">用户名</label>
            <div class="col-sm-3">
                <input name="name" type="text" class="form-control" placeholder="请输入用户名">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">密码</label>
            <div class="col-sm-3">
                <input name="password" type="password" class="form-control" placeholder="请输入密码">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-3 col-sm-offset-3">
                <button class="btn btn-primary">点击登录</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>
<!--结果页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}登录结果</title>
</head>
<body>
<div class="container">

    <div class="row">
        <h3 class="col-sm-3 col-sm-offset-3">登录结果</h3>
    </div>
    <div class="row">
        <label class="col-sm-3 col-sm-offset-3">姓名:${name} </label>
    </div>
    <div class="row">
        <label class="col-sm-3 col-sm-offset-3"> ${result}</label>
    </div>
</div>
</body>
</html>

7.2 特殊的监听器

public class User implements javax.servlet.http.HttpSessionBindingListener {
    private String name;

    public User(String name){
        this.name=name;
    }

    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(name+"加入session");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println(name+"移出session");
    }
}

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
  		...
        // 测试HttpSessionBindingListener
        req.getSession().setAttribute("user",new User(name));
}

在这里插入图片描述


八、过滤器

  • Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。
  • 通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截。简单说,就是可以实现web容器对某资源的访问前截获进行相关的处理,还可以在某资源向web容器返回响应前进行截获进行处理。

在这里插入图片描述

8.1 过滤器的使用方法

/**
 * 过滤器例子
 */
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 过滤
        System.out.println("拦截过滤...");
        // 放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
<!-- web.xml -->
    <!-- 过滤器配置 -->
    <filter>
        <filter-name>filterDemo</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <!-- 拦截路径 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

8.2 过滤器的执行流程

	@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 前置过滤
        System.out.println("拦截过滤{pre}");
        // 放行请求
        filterChain.doFilter(servletRequest,servletResponse);
        // 后置过滤
        System.out.println("拦截过滤{post}");
    }

在这里插入图片描述

8.3 过滤器的生命周期

  1. 初始化init:服务器启动时,进行创建Filter对象,然后调用init方法;该过程只执行一次,一般用于加载资源。
  2. 拦截过滤doFilter:每一次请求被都会被执行。
  3. 销毁destroy:服务器正常关闭时,Filter对象会被销毁。该过程只执行一次,一般用于释放资源。

8.4 过滤器的拦截配置

  1. 拦截具体资源:比如/index.jsp,只有访问index.jsp资源时,过滤器才会执行。
  2. 拦截网站目录:/demo ,访问网站的demo目录下的资源时,过滤器才会执行。
  3. 后缀名拦截:比如 *.jsp,访问所有后缀名为jsp资源时,过滤器会执行。
  4. 拦截所有资源:比如/*,访问网站下所有资源时,过滤器都会执行。
	<!-- 拦截具体资源 -->
 	<filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/form.jsp</url-pattern>
    </filter-mapping>
	<!-- 拦截网站目录 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/demo</url-pattern>
    </filter-mapping>
	<!-- 后缀名拦截 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
	<!-- 拦截所有资源 -->
    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  1. REQUEST : 浏览器直接请求时,过滤器才会执行。
  2. FORWARD: 只有转发访问时,过滤器才会执行。
  3. INCLUDE:包含访问资源时,过滤器才会执行。
  4. ERROR:错误跳转资源时,过滤器才会执行。
  5. ASYNC:异步访问资源时,过滤器才会执行。
 <!-- 过滤器配置 -->
    <filter>
        <filter-name>filterDemo</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>filterDemo</filter-name>
        <url-pattern>/http-demo</url-pattern>
        <!-- 浏览器直接请求时,过滤器会执行 -->
        <dispatcher>REQUEST</dispatcher>
        <!-- 转发请求时,过滤器会执行 -->
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

8.5 过滤器链

<!-- 过滤器配置  -->
    <filter>
        <filter-name>filterDemo1</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>
    <!-- 哪个过滤器的filter-mapping先配置,则哪个过滤器先执行-->
    <filter-mapping>
        <filter-name>filterDemo1</filter-name>
        <url-pattern>/http-demo</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>filterDemo2</filter-name>
        <filter-class>demo.filter.FilterDemo2</filter-class>
    </filter>
    <!-- 哪个过滤器的filter-mapping后配置,则哪个过滤器后执行-->
    <filter-mapping>
        <filter-name>filterDemo2</filter-name>
        <url-pattern>/http-demo</url-pattern>
    </filter-mapping>

在这里插入图片描述

8.5 过滤器的案例--登录验证

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <context-param>
        <param-name>title</param-name>
        <param-value>购物网站</param-value>
    </context-param>

    <!-- 过滤器配置  -->
    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>demo.filter.FilterDemo</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 登录验证servlet -->
    <servlet>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>demo.servlet.LoginServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <!-- 购物车servlet -->
    <servlet>
        <servlet-name>cart</servlet-name>
        <servlet-class>demo.servlet.CartServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>cart</servlet-name>
        <url-pattern>/cart</url-pattern>
    </servlet-mapping>

</web-app>
/**
 * 购物网站登录页面
 *
 * @author zhuhuix
 * @date 2020-08-30
 */
public class LoginServlet extends HttpServlet {

    // 重写Get请求方法,返回一个登录页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setAttribute("title", getServletContext().getInitParameter("title"));
        req.getRequestDispatcher("/form.jsp").forward(req, resp);

    }

    // 重写Post请求方法,提交用户名与密码
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("name");
        Integer password = Integer.parseInt(req.getParameter("password"));
        if (name != null && password != null) {
            // 用户登录验证通过后,设置用户名称属性
            req.getSession().setAttribute("name",name);
            RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
            view.forward(req, resp);
        }

    }
}
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}用户登录</title>
</head>
<body>
<div class="container">

    <form role="form" method="post" action="login" class="form-horizontal">
        <div class="form-group">
            <h4 class="col-sm-3 col-sm-offset-3">用户登录</h4>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">用户名</label>
            <div class="col-sm-3">
                <input name="name" type="text" class="form-control" placeholder="请输入用户名">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">密码</label>
            <div class="col-sm-3">
                <input name="password" type="password" class="form-control" placeholder="请输入密码">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-3 col-sm-offset-3">
                <button class="btn btn-primary">点击登录</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

在这里插入图片描述

/**
 * 购物车Servlet
 *
 * @author zhuhuix
 * @date 2020-08-29
 */
public class CartServlet extends javax.servlet.http.HttpServlet {


    // 重写Post请求方法,提交购物车的数据,并返回结果页面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查找页面上的购物数量,并放入session中

        req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
        req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
        req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));

        RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
        view.forward(req, resp);
    }
}
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
            integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
            crossorigin="anonymous"></script>
    <title>${title}购物车</title>
</head>
<body>
<div class="container">

    <form role="form" method="post" action="cart" class="form-horizontal">
        <div class="form-group">
            <h4 class="col-sm-3 col-sm-offset-1">${name}的购物车</h4>
        </div>
        <table class="table table-bordered table-condensed" style="width: 30%">
            <thead>
            <tr>
                <td>货物</td>
                <td>数量</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>手机</td>
                <td><input type="number" name="phoneNumber" value=${phoneNumber}> </td>
            </tr>
            <tr>
                <td>电脑</td>
                <td><input type="number" name="pcNumber" value=${pcNumber}> </td>
            </tr>
            <tr>
                <td>书本</td>
                <td><input type="number" name="bookNumber" value=${bookNumber}> </td>
            </tr>
            </tbody>
        </table>

        <div class="form-group">
            <div class="col-sm-1 col-sm-offset-1">
                <button class="btn btn-primary">点击提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

在这里插入图片描述

  1. 访问购物车页面:由于用户未登录,则会跳转到登录页面
    在这里插入图片描述

  2. 用户输入用户名和密码后进行登录,登录成功后会跳转到购物车页面。
    在这里插入图片描述
    在这里插入图片描述

  3. 用户进行购物,并提交购物结果
    在这里插入图片描述
    在这里插入图片描述

  4. 退出页面,在浏览器中再次访问购物车页面,可以看到过滤器判断到用户会话存在,已处于登录状态,直接跳转到购物车页面

在这里插入图片描述

标签:Web,Java,请求,技术细节,resp,req,过滤器,void,name
来源: https://www.cnblogs.com/zhuhuix/p/13587689.html