JavaWeb Servlet基本介绍和使用案例(含session)

1. Servlet的基本介绍

Servlet获取客户端发送给Servlet服务的数据,然后对数据进行操作。比如HTML页面的form表单,用户在表单输入各种数据,然后点击submit进行提交

2. Servlet的使用案例

2.1 web/index.html

web/index.html的内容,是一个简单的form表单,其中action是printData。如下所示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="printData" method="post" name="print_data_form">

    用户名: <input type="text" name="username" value="" maxlength="10" /> <br />

    <input type="submit" name="submit" value="提交"/> <br />

</form>

</body>
</html>

2.1 web/WEB-INF/web.xml

web/WEB-INF/web.xml文件。说明如下:

  • form表单的action printData对应url-pattern
  • 然后映射到servlet-name
  • 最后映射到servlet-class
  • 由servlet-class处理action printData操作

文件内容如下:

<?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>printDataServlet</servlet-name>
        <servlet-class>com.hh.javaWebTest.PrintDataServlet</servlet-class>
        <!-- 配置Servlet启动顺序。数字越小越先启动,最小为0 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>printDataServlet</servlet-name>
        <url-pattern>/printData</url-pattern>
    </servlet-mapping>
    
</web-app>

2.3 PrintDataServlet.java

下面进行Servlet类的编写,先在pom.xml添加依赖

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>10.1.1</version>
        </dependency>

src\main\java\com\hh\javaWebTest\PrintDataServlet.java内容如下。继承HttpServlet类,然后重写doPost方法,由HttpServletRequest获取form表单的数据。然后就可以对获取的数据进行各种操作

package com.hh.javaWebTest;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;


import java.io.IOException;

public class PrintDataServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);

        // 默认为true, 如果没有创建session,则会自动创建一个session。false表示如果没有session则返回null
        HttpSession session = req.getSession(true);
        String sessionId = session.getId();
        System.out.println("session id是: " + sessionId);

        /* 其它常用API:
        session.isNew();
        // 默认1800秒
        session.getMaxInactiveInterval();
        session.setMaxInactiveInterval(1800);
        // 强制性让会话立即失效
        session.invalidate();
        
        // 向session中保存key-value的数据
        session.setAttribute("key", "value");
        session.getAttribute("key");
         */

        // req.getRequestDispatcher("printData2").forward(req, resp);
        // resp.sendRedirect("printData2");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // post方式设置编码,防止中文乱码, 必须在获取任何数据前设置。get方式不需要设置
        req.setCharacterEncoding("UTF-8");
        
        String username = req.getParameter("username");

        System.out.println("获取到的用户名: " + username);
    }
}

会话跟踪技术:客户端非第一次给服务器发请求,会带上sessionID,那么服务器就能确定是否是同一客户端
服务端转发:由req.getRequestDispatcher("printData2").forward(req, resp);实现。客户端请求printData,由服务端内部转发到printData2进行处理,该过程客户端感知不到,客户端在浏览器请求的url不变,全程由printData为客户端服务
客户端重定向:由resp.sendRedirect("printData2");实现,该语句后必须不能含语句或只含return语句。服务端告诉客户端去请求printData2,此时客户端在浏览器请求的url变成printData2,后续由printData2为客户端服务

2.4 Servlet测试

在IDEA中重新运行Tomcat Server,然后访问http://localhost:8080/javaWebTest/index.html。输入用户名张三,然后点击提交按钮进行表单提交操作

提交表单查看Network,可以看到会跳转到http://localhost:8080/javaWebTest/printData,请求方式是POST
Network查看
IDEA中的Tomcat Server日志处会打印Servlet的输出,如下所示:
Tomcat日志

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值