Skip to content

Servlet及Filter基础实验

1 实验类型

验证型,2学时,必选实验

2 实验目的

掌握Servlet程序的编写方法;理解前后端数据传输原理;

3 实验要求

验证参考代码;修改参考代码,实现自己的设计;将关键结果截图及源代码整理成实验报告

4 实验环境

Windows 7 64、Open JDK 23+、Tomcat 11+、Spring Tools 4(STS4)、Visual Studio Code(VS Code)、Microsoft Edge/Chrome/Firefox等浏览器 、sqlite-jdbc-3.41.0.0.jar

5 实验步骤

创建工作目录:{盘符}:/{学号}/exp4_servlet

通过两种不同方式(配置文件方式、注解方式)创建Servlet,步骤如下:

配置文件方式

  1. 创建的Dynamic Web工程:HelloServlet

    注意:勾选Generate web.xml deployment descriptor

  2. 增加Tomcat容器;执行Window->Preferences/Server/Runtime Enviroments/Add,增加Tomcat容器

  3. 增加Servlet相关包;执行Build Path->Configure Build path->Libraries->Add Library->Server Runtime,增加Server Runtime[Apache Tomcat v11+]

    注意:缺少本步骤则无法访问Servlet

  4. 注册Tomcat;在Servers视图中注册本机Tomcat

  5. 创建包Hello;在src节点下创建包Hello

  6. 创建Servlet类:Hello.Hello1,参考代码如下:

    Hello.Hello1类
    package Hello;
    
    import java.io.IOException;
    import jakarta.servlet.ServletConfig;
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    
    public class Hello1 extends HttpServlet {
      private static final long serialVersionUID = 1L;
    
      private String message;
    
      public Hello1() {
      }
    
      public void init(ServletConfig config) throws ServletException {
        message = "Hello World!";
      }
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.getWriter().append("<h1>" + message + "</h1>");
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
      }
    
    }
    
  7. web.xml中注册Hello1类,参考配置如下:

    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="https://jakarta.ee/xml/ns/jakartaee"
        xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
        id="WebApp_ID" version="5.0">
        <display-name>HelloServlet</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.jsp</welcome-file>
            <welcome-file>default.htm</welcome-file>
        </welcome-file-list>
    
        <servlet>
            <servlet-name>Hello1</servlet-name>
            <servlet-class>Hello.Hello1</servlet-class> 
        </servlet>
        <servlet-mapping>
            <servlet-name>Hello1</servlet-name>
            <url-pattern>/hello1</url-pattern>
        </servlet-mapping>
    </web-app>
    
  8. 部署工程到Tomat并启动

  9. 在浏览器中访问http://localhost:8080/HelloServlet/Hello1并观察结果是否正确

注解方式

  1. 创建基于注解的Servlet类:Hello.Hello2,参考代码如下:

    Hello.Hello2类
    package Hello;
    
    import java.io.IOException;
    import jakarta.servlet.ServletConfig;
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    
    @WebServlet("/Hello2")
    public class Hello2 extends HttpServlet {
      private static final long serialVersionUID = 1L;
    
      private String message;
    
      public Hello2() {
      }
    
      public void init(ServletConfig config) throws ServletException {
        message = "Hello World Again!";
      }
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.getWriter().append("<h1>" + message + "</h1>");
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
      }
    
    }
    
  2. 在浏览器中访问http://localhost:8080/HelloServlet/Hello2并观察结果是否正确

处理表单数据

使用Servlet实现加法运算,表单页面(AddForm.jsp)用GET/POST两种方式采集操作数,Servlet类(AddServlet)计算两个操作数的和并将结果返回给客户端,步骤如下:

GET方式

  1. 创建页面:AddForm.jsp,用于收集信息,参考代码下:

    AddForm.jsp
    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
    <!DOCTYPE html>
    <html>
    
    <body>
      <form action="add" method="GET">
        a:<input type="text" name="a" /> <br />
        b:<input type="text" name="b" /> <br />
        <input type="submit" value="求和" />
      </form>
    </body>
    
    </html>
    

    注意:表单的提交方式为GET

  2. 创建表单数据处理Servlet类:Hello.AddServlet,在doGet方法中处理表单参数,参考代码如下:

    Hello.AddServlet类
    package Hello;
    
    import java.io.IOException;
    import jakarta.servlet.ServletConfig;
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    
    @WebServlet("/add")
    public class AddServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
    
      public AddServlet() {
        super();
      }
    
      public void init(ServletConfig config) throws ServletException {
      }
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setHeader("content-type", "text/html;charset=utf-8");
        String message = "a+b=";
        try {
          Float a = Float.parseFloat(request.getParameter("a"));
          Float b = Float.parseFloat(request.getParameter("b"));
          message += a + b;
        } catch (Exception e) {
    
        }
    
        response.getWriter().write(message);
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
      }
    
    }
    
  3. 部署工程并在浏览器中访问http://localhost:8080/HelloServlet/AddForm.jsp

  4. 在表单中填写信息并提交,观察页面变化,确认是否为AddServlet返回的结果

POST方式

  1. AddForm.jsp中表单的提交方式改为POST

  2. 在AddServlet类的doPost增加处理表单参数代码,参考上步代码

  3. 重新访问http://localhost:8080/HelloServlet/AddForm.jsp

处理Session信息

编写新的Servlet类访问Session对象的信息并在显示在页面中。Sessioin对象主要方法如下:

方法 功能
public Object getAttribute(String name) 该方法返回在该 session 会话中具有指定名称的对象,如果没有指定名称的对象,则返回 null。
public Enumeration getAttributeNames() 该方法返回 String 对象的枚举,String 对象包含所有绑定到该 session 会话的对象的名称。
public long getCreationTime() 该方法返回该 session 会话被创建的时间,自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
public String getId() 该方法返回一个包含分配给该 session 会话的唯一标识符的字符串。
public long getLastAccessedTime() 该方法返回客户端最后一次发送与该 session 会话相关的请求的时间自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
public int getMaxInactiveInterval() 该方法返回 Servlet 容器在客户端访问时保持 session 会话打开的最大时间间隔,以秒为单位。
public void invalidate() 该方法指示该 session 会话无效,并解除绑定到它上面的任何对象。
public boolean isNew() 如果客户端还不知道该 session 会话,或者如果客户选择不参入该 session 会话,则该方法返回 true。
public void removeAttribute(String name) 该方法将从该 session 会话移除指定名称的对象。
public void setAttribute(String name, Object value) 该方法使用指定的名称绑定一个对象到该 session 会话。
public void setMaxInactiveInterval(int interval) 该方法在 Servlet 容器指示该 session 会话无效之前,指定客户端请求之间的时间,以秒为单位。

具体步骤如下:

  1. 创建Servlet类:Hello.SessionServlet,参考代码如下:

    Hello.SessionServlet类
    package Hello;
    
    import java.io.IOException;
    import jakarta.servlet.ServletConfig;
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import jakarta.servlet.http.HttpSession;
    
    @WebServlet("/getSessionInfo")
    public class SessionServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
    
      public SessionServlet() {
        super();
      }
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setHeader("content-type", "text/html;charset=utf-8");
    
        String info = "<h3>Session Infomation</h3>\n";
        info += String.format("<p>Creation Time:%s</p>\n", session.getCreationTime());
        info += String.format("<p>Session Id:%s</p>\n", session.getId());
        info += String.format("<p>Last Accessed Time:%s</p>\n", session.getLastAccessedTime());
        info += String.format("<p>Max Inactive Interval:%s</p>\n", session.getMaxInactiveInterval());
    
        response.getWriter().append(info);
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
      }
    
    }
    
  2. 重新部署后在浏览器中访问http://localhost:8080/HelloServlet/getSessionInfo

综合

使用Servlet实现基于四层架构(实体层、数据访问层、服务层、控制层)的学生表的增操作,使用Sqlite(或其它数据库)在服务端存储数据,4层架构如下:

graph LR classDef process fill:#E5F6FF,stroke:#73A6FF,stroke-width:2px; subgraph "表现层 (Action)" A(JSP页面):::process end subgraph "业务逻辑层 (Service)" B(StudentService):::process end subgraph "数据访问层 (DAO)" C(StudentDAO):::process end subgraph "实体层 (Domain)" D(Student):::process end A -->|调用业务方法| B B -->|调用数据访问方法| C C -->|操作实体| D classDef database fill:#FFEBEB,stroke:#E68994,stroke-width:2px; E[(学生表)]:::database C -->|CRUD 操作| E

Web API如下:

url 功能
/demo/Student/Add 添加学生
/demo/Student/Get 查询学生

参考步骤如下:

  1. 创建Java Web工程DaoTest

  2. sqlite-jdbc-3.49.1.0.jar放入WEB-INF/lib

    详见实验目录

  3. 创建实体类:xust.demo.stu.domain.Student,参考代码如下:

    xust.demo.stu.domain.Student类
    package xust.demo.stu.domain;
    
    /**
     * Class Student
     * 学生表
     * 
     * @author XUST
     * @version 1.0, 2023-04-20
     */
    public class Student {
    
      /**
       * 学号
       */
      private String no;
    
      public String getNo() {
        return no;
      }
    
      public void setNo(String newValue) {
        no = newValue;
      }
    
      /**
       * 姓名
       */
      private String name;
    
      public String getName() {
        return name;
      }
    
      public void setName(String newValue) {
        name = newValue;
      }
    
      /**
       * 性别
       */
      private String gender;
    
      public String getGender() {
        return gender;
      }
    
      public void setGender(String newValue) {
        gender = newValue;
      }
    
      /**
       * 年龄
       */
      private Integer age;
    
      public Integer getAge() {
        return age;
      }
    
      public void setAge(Integer newValue) {
        age = newValue;
      }
    
      /**
       * 所在系
       */
      private String dept;
    
      public String getDept() {
        return dept;
      }
    
      public void setDept(String newValue) {
        dept = newValue;
      }
    
      @Override
      /**
       * 将对象序列化为JSON字符串
       */
      public String toString() {
        return "{" + "\"no\": " + "\"" + no + "\"" + ", " + "\"name\": " + "\"" + name + "\"" + ", " + "\"gender\": " + "\""
            + gender + "\"" + ", " + "\"age\": " + age + ", " + "\"dept\": " + "\"" + dept + "\"" + "}";
      }
    }
    
  4. 创建数据库连接类:xust.demo.ConnectionUtil,数据库文件存放在:d:/stu.db,无需手动创建,代码会自动创建,参考代码如下:

    xust.demo.ConnectionUtil类
    package xust.demo;
    
    import java.sql.*;
    
    /**
     * 连接辅助类
     */
    public class ConnectionUtil {
      /**
       * 创建连接
       * 
       * @return 连接对象
       */
      public static Connection getConnection() {
        Connection res = null;
    
        try {
          Class.forName("org.sqlite.JDBC");
          // 在数据库文件stu.db存放在D盘下
          res = DriverManager.getConnection("jdbc:sqlite:d:/stu.db");
        } catch (Exception e) {
          System.err.println(e.getClass().getName() + ": " + e.getMessage());
          System.exit(0);
        }
    
        return res;
      }
    
      /**
       * 关闭连接
       * 
       * @param connection 连接对象
       */
      public static void closeConnection(Connection connection) {
        if (connection != null) {
          try {
            connection.close();
          } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
          }
        }
      }
    
      /**
       * 关闭语句
       * 
       * @param pstmt 语句对象
       */
      public static void closePstmt(PreparedStatement pstmt) {
        if (pstmt != null) {
          try {
            pstmt.close();
          } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
          }
        }
      }
    
      /**
       * 关闭语句
       * 
       * @param pstmt 语句对象
       */
      public static void closeStmt(Statement stmt) {
        if (stmt != null) {
          try {
            stmt.close();
          } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
          }
        }
      }
    }
    
  5. 创建结果实体类:xust.demo.Result,参考代码如下:

    xust.demo.Result类
    package xust.demo;
    
    /**
     * 操作结果类
     */
    public class Result {
    
      /**
       * 结果码,0为成功
       */
      public int code;
    
      /**
       * 结果信息
       */
      public String message;
    
      /**
       * 结果数据
       */
      public Object data;
    
      public Result() {
    
      }
    
      public Result(Boolean v) {
        code = v ? 0 : 1;
      }
    }
    
  6. 创建数据访问接口:xust.demo.stu.dao.StudentDao和实现类:xust.demo.stu.dao.StudentDaoImpl,参考代码如下:

    xust.demo.stu.dao.StudentDao接口
    package xust.demo.stu.dao;
    
    import xust.stu.Result;
    import xust.demo.stu.domain.Student;
    
    public interface StudentDao {
      /**
       * 初始化表
       * 
       * @return
       */
      Result init();
    
      /**
       * 增
       * 
       * @param o
       * @return
       */
      Result create(Student o);
    
      /**
       * 删
       * 
       * @param id
       * @return
       */
      Result delete(String no);
    
      /**
       * 改
       * 
       * @param o
       * @return
       */
      Result update(Student o);
    
      /**
       * 查
       * 
       * @param no
       * @return
       */
      Result get(String no);
    
      /**
       * 查
       * 
       * @return
       */
      Result getAll();
    }
    
    xust.demo.stu.dao.StudentDaoImpl类
    package xust.demo.stu.dao;
    
    import java.sql.*;
    import java.util.ArrayList;
    import xust.stu.Result;
    import xust.stu.ConnectionUtil;
    import xust.demo.stu.domain.Student;
    
    public class StudentDaoImpl implements StudentDao {
      public Result init() {
        Result res = new Result(false);
    
        Connection con = null;
        Statement stmt = null;
        String sql = "create table Student(" +
            "no TEXT primary key," +
            "name TEXT not null," +
            "gender TEXT," +
            "age INTEGER," +
            "dept TEXT" +
            ");";
    
        con = ConnectionUtil.getConnection();
        if (con != null) {
          try {
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(String.format(
                "select count(*) from sqlite_master where type = 'table' and Upper(name) = '%s'", "Student".toUpperCase()));
            while (rs.next()) {
              int count = rs.getInt(1);
    
              if (count == 0 && stmt.executeUpdate(sql) > 0) {
                res.code = 0;
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
            res.message = e.getMessage();
          } finally {
            ConnectionUtil.closeStmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    
      /**
       * 对象填充到关系
       */
      private void toR(Student o, PreparedStatement stmt) throws Exception {
        if (o != null && stmt != null) {
          String no = o.getNo();
          if (no != null) {
            stmt.setString(1, no);
          }
          String name = o.getName();
          if (name != null) {
            stmt.setString(2, name);
          }
          String gender = o.getGender();
          if (gender != null) {
            stmt.setString(3, gender);
          }
          Integer age = o.getAge();
          if (age != null) {
            stmt.setInt(4, age);
          }
          String dept = o.getDept();
          if (dept != null) {
            stmt.setString(5, dept);
          }
        }
      }
    
      /**
       * 关系填充到对象
       */
      private Student toO(ResultSet rs) throws Exception {
        Student res = null;
    
        if (rs != null) {
          res = new Student();
          res.setNo(rs.getString("no"));
          res.setName(rs.getString("name"));
          res.setGender(rs.getString("gender"));
          res.setAge(rs.getInt("age"));
          res.setDept(rs.getString("dept"));
        }
    
        return res;
      }
    
      public Result create(Student o) {
        Result res = new Result(false);
    
        Connection con = null;
        PreparedStatement stmt = null;
        String sql = "insert into Student values (?, ?, ?, ?, ?)";
        con = ConnectionUtil.getConnection();
        if (o != null && con != null) {
          try {
            stmt = con.prepareStatement(sql);
            toR(o, stmt);
            int row_effected = stmt.executeUpdate();
            if (row_effected > 0) {
              res.code = 0;
            }
            res.data = row_effected;
          } catch (Exception e) {
            res.message = e.getMessage();
            e.printStackTrace();
          } finally {
            ConnectionUtil.closePstmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    
      public Result delete(String no) {
        Result res = new Result(false);
    
        Connection con = null;
        PreparedStatement stmt = null;
        String sql = "delete from Student where no = ?;";
        con = ConnectionUtil.getConnection();
        if (con != null) {
          try {
    
            stmt = con.prepareStatement(sql);
            stmt.setString(1, no);
            int row_effected = stmt.executeUpdate();
            if (row_effected > 0) {
              res.code = 0;
            }
            res.data = row_effected;
          } catch (Exception e) {
            res.message = e.getMessage();
            e.printStackTrace();
          } finally {
            ConnectionUtil.closePstmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    
      public Result update(Student o) {
        Result res = new Result(false);
    
        Connection con = null;
        PreparedStatement stmt = null;
        String sql = "update Student set No = ?, Name = ?, Gender = ?, Age = ?, Dept = ? where no = ?";
        con = ConnectionUtil.getConnection();
        if (o != null && con != null) {
          try {
    
            stmt = con.prepareStatement(sql);
            toR(o, stmt);
            stmt.setString(6, o.getNo());
            int row_effected = stmt.executeUpdate();
            if (row_effected > 0) {
              res.code = 0;
            }
            res.data = row_effected;
          } catch (Exception e) {
            e.printStackTrace();
            res.message = e.getMessage();
          } finally {
            ConnectionUtil.closePstmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    
      public Result get(String no) {
        Result res = new Result(false);
    
        Connection con = null;
        PreparedStatement stmt = null;
        String sql = "select * from Student where no = ?";
        con = ConnectionUtil.getConnection();
        if (con != null) {
          try {
            stmt = con.prepareStatement(sql);
            stmt.setString(1, no);
            ResultSet rs = stmt.executeQuery();
            Student last = null;
            while (rs.next()) {
              last = new Student();
              last.setNo(rs.getString("no"));
              last.setName(rs.getString("name"));
              last.setGender(rs.getString("gender"));
              last.setAge(rs.getInt("age"));
              last.setDept(rs.getString("dept"));
            }
    
            res.code = 0;
            res.data = last;
          } catch (Exception e) {
            res.message = e.getMessage();
            e.printStackTrace();
          } finally {
            ConnectionUtil.closePstmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    
      public Result getAll() {
        Result res = new Result(false);
    
        Connection con = null;
        PreparedStatement stmt = null;
        String sql = "select * from Student";
        con = ConnectionUtil.getConnection();
        if (con != null) {
          try {
            stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            ArrayList<Student> data = new ArrayList<Student>();
            while (rs.next()) {
              Student last = toO(rs);
              data.add(last);
            }
    
            res.code = 0;
            res.data = data;
          } catch (Exception e) {
            res.message = e.getMessage();
            e.printStackTrace();
          } finally {
            ConnectionUtil.closePstmt(stmt);
            ConnectionUtil.closeConnection(con);
          }
        }
    
        return res;
      }
    }
    
  7. 创建服务接口:xust.demo.stu.service.StudentService和实现类:xust.demo.stu.service.StudentServiceImpl,参考代码如下:

    xust.demo.stu.serviceStudentService接口
    package xust.demo.stu.service;
    
    import xust.stu.Result;
    import xust.demo.stu.domain.Student;
    import jakarta.servlet.http.HttpServletRequest;
    
    public interface StudentService {
      Student toO(HttpServletRequest request);
    
      /**
       * 增
       * 
       * @param o
       * @return
       */
      Result create(Student o);
    
      /**
       * 删
       * 
       * @param id
       * @return
       */
      Result delete(String no);
    
      /**
       * 改
       * 
       * @param o
       * @return
       */
      Result update(Student o);
    
      /**
       * 查
       * 
       * @param no
       * @return
       */
      Result get(String no);
    
      /**
       * 查
       * 
       * @return
       */
      Result getAll();
    }
    
    xust.demo.stu.service.StudentServiceImpl类
    package xust.demo.stu.service;
    
    import jakarta.servlet.http.HttpServletRequest;
    import xust.stu.Result;
    import xust.demo.stu.domain.Student;
    import xust.demo.stu.dao.StudentDao;
    import xust.demo.stu.dao.StudentDaoImpl;
    
    public class StudentServiceImpl implements StudentService {
      private StudentDao _StudentDao;
    
      public StudentServiceImpl() {
        _StudentDao = new StudentDaoImpl();
        _StudentDao.init();
      }
    
      /**
       * 参数填充到对象
       */
      public Student toO(HttpServletRequest request) {
        Student res = null;
    
        if (request != null) {
          res = new Student();
          String p = null;
          p = request.getParameter("no");
          if (p != null) {
            res.setNo(request.getParameter("no"));
          }
          p = request.getParameter("name");
          if (p != null) {
            res.setName(request.getParameter("name"));
          }
          p = request.getParameter("gender");
          if (p != null) {
            res.setGender(request.getParameter("gender"));
          }
          p = request.getParameter("age");
          if (p != null) {
            res.setAge(Integer.parseInt(request.getParameter("age")));
          }
          p = request.getParameter("dept");
          if (p != null) {
            res.setDept(request.getParameter("dept"));
          }
        }
    
        return res;
      }
    
      public Result create(Student o) {
        Result res = new Result(false);
    
        if (_StudentDao != null && o != null) {
          res = _StudentDao.create(o);
        }
    
        return res;
      }
    
      public Result delete(String no) {
        Result res = new Result(false);
    
        if (_StudentDao != null) {
          res = _StudentDao.delete(no);
        }
    
        return res;
      }
    
      public Result update(Student o) {
        Result res = new Result(false);
    
        if (_StudentDao != null && o != null) {
          res = _StudentDao.update(o);
        }
    
        return res;
      }
    
      public Result get(String no) {
        Result res = new Result(false);
    
        if (_StudentDao != null) {
          res = _StudentDao.get(no);
        }
    
        return res;
      }
    
      public Result getAll() {
        Result res = new Result(false);
    
        if (_StudentDao != null) {
          res = _StudentDao.getAll();
        }
    
        return res;
      }
    }
    
  8. 创建控制Servlet:StudentAddServlet,参考代码如下:

    xust.demo.stu.action.StudentAddServlet类
    package xust.demo.stu.action;
    
    import java.io.IOException;
    
    import jakarta.servlet.ServletException;
    import jakarta.servlet.annotation.WebServlet;
    import jakarta.servlet.http.HttpServlet;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import xust.stu.Result;
    import xust.demo.stu.domain.Student;
    import xust.demo.stu.service.StudentService;
    import xust.demo.stu.service.StudentServiceImpl;
    
    @WebServlet("/demo/Student/Add")
    public class StudentAddServlet extends HttpServlet {
      private StudentService _StudentService = new StudentServiceImpl();
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    
        Student o = _StudentService.toO(request);
        Result res = _StudentService.create(o);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter()
            .append(String.format("{\"code\":%d, \"message\":\"%s\", \"data\":\"%s\"}", res.code, res.message, res.data));
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
      }
    }
    
  9. 编写测试代码:StudentServletTest.http(Rest Client脚本),参考代码如下:

    DaoTest/StudentServletTest.http
    @app = DaoTest
    
    ### 增
    POST http://localhost:8080/{{app}}/demo/Student/Add HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    no=X2
    &name=X2
    &gender=X2
    &age=2
    &dept=X2
    
    ### 删
    POST http://localhost:8080/{{app}}/demo/Student/Delete HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    no=X2
    
    ### 改
    POST http://localhost:8080/{{app}}/demo/Student/Update HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    no=X2
    &name=3
    &gender=3
    &age=3
    &dept=3
    
    ### 查
    POST http://localhost:8080/{{app}}/demo/Student/Get HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    no=X2
    
  10. 分别发送请求,验证代码可以正常工作

拓展练习

  1. 使用Servlet实现课程表的增操作