Skip to content

JSP的隐含对象实验

1 实验类型

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

2 实验目的

掌握JSP基本语法;掌握对JSP各隐含对象的功能;掌握JSP隐含对象的使用方法;理解前后端数据交换过程

3 实验要求

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

4 实验环境

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

5 实验步骤

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

创建测试工程

创建名为BuiltInTest的动态Web工程,后续步骤在该工程中展开,参考步骤如下:

  1. 创建工程;在STS4中创建的Dynamic Web工程:BuiltInTest

    注意:勾选Generate web.xml deployment descriptor

request对象

编写两个JSP页面,实现以下功能:在一个页面(RequestClient.jsp)页面中填写表单数据,提交至另一个页面(RequestServer.jsp),该页面显示表单提交的数据,参考步骤如下:

  1. 创建表单页面:RequestClient.jsp,通过该页面提交参数给页面RequestServer.jsp,参考代码如下:

    RequestClient.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    
    <body>
      <form action="RequestServer.jsp" method="POST" name="form">
        <input type="text" name="boy"> 
        <input type="submit" value="Enter" name="submit">
      </form>
    </body>
    
    </html>
    
  2. 创建接收页面:RequestServer.jsp处理RequestClient.jsp页面提交的参数,参考代码如下:

    RequestServer.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    
    <body>
      <p>
        获取文本框提交的信息:
        <% String textContent = request.getParameter("boy"); %><br>
        <%=textContent%>
      </p>
      <p>
        获取按钮的名字:
        <% String buttonName = request.getParameter("submit"); %><br>
        <%=buttonName%>
      </p>
    </body>
    
    </html>
    
  3. 测试;在浏览器中访问http://localhost:8080/BuiltInTest/RequestClient.jsp,在文本框中输入任意字符串(如:Jack)后点击Enter观察浏览器地址栏及页面内容变化

respone对象

编写三个JSP页面,实现以下功能:通过登录页面(ResponseLogin.jsp)向控制页面(ResponseCheck.jsp)提交用户认证信息,通过认证则在原地显示欢迎信息,否则引导至错误页面(ResponseFail.jsp),参考步骤如下:

  1. 创建登录页面:ResponseLogin.jsp,实现登录界面,参考代码如下:

    ResponseLogin.jsp
    <%@ page contentType="text/html;charset=utf-8" %>
      <html>
    
      <head>
        <meta charset="utf-8">
      </head>
    
      <body>
        填写姓名:
        <br>
        <form action="ResponseCheck.jsp" method="GET" name="form">
          <input type="text" name="name">
          <input type="submit" value="Enter">
        </form>
      </body>
    
      </html>
    
  2. 创建控制页面:ResponseCheck.jsp,实现认证信息检查,参考代码如下:

    ResponseCheck.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <%
      String str = null;
      str = request.getParameter("name");
      if (str == null) {
        str = "";
      }
      byte b[] = str.getBytes("ISO-8859-1");
      str = new String(b);
      if (str.equals("")) {
        response.sendRedirect("ResponseFail.jsp");
      } else {
        out.print("欢迎您来到本网页!");
        out.print(str);
      }
      %>
    </body>
    </html>
    
  3. 创建失败页面:ResponseFail.jsp,提示认证失败信息,参考代码如下:

    ResponseFail.jsp
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <%@ page contentType="text/html;charset=utf-8" %>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      请输入用户名!
    </body>
    </html>
    
  4. 测试;在浏览器中打开http://localhost:8080/BuiltInTest/ResponseLogin.jsp,输入任一字符串(如:Jack)点击Enter,观察地址栏和页面的变化

session对象

创建三个JSP页面,实现如下功能:入口页面(SessionClient.jsp)中包含提交至接收页面SessionTom.jsp的表单,后者页面中包含跳转至页面SessionJerry.jsp的超链接,在每个页面中显示Session Id,并在不同页面之间跳转过程中,观察Session Id的变化,参考步骤如下:

  1. 创建初始页面:SessionClient.jsp,作为入口显示当前session的id,参考代码如下:

    SessionClient.jsp
    <%@ page contentType="text/html;charset=utf-8" %>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    
    <body>
      <p>
        <% String s=session.getId(); %>
      </p>
      <p>
        您的session对象的ID是:<br>
        <%=s%>
      </p>
      <p>输入你的姓名连接到tom.jsp
      <form action="SessionTom.jsp" method="POST" name="form">
        <input type="text" name="name">
        <input type="submit" value="送出" name=submit>
      </form>
      </p>
    </body>
    
    </html>
    
  2. 创建中间页面:SessionTom.jsp,参考代码如下:

    SessionTom.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <p>我是Tom页面<%String s = session.getId();%></p>
      <p>您的在Tom页面中的session对象的ID是:<%=s%></p>
      <p>点击超链接,连接到Jerry的页面。 <br> 
        <a href="SessionJerry.jsp">欢迎到Jerry屋来!</a>
      </p>
    </body>
    </html>
    
  3. 创建结束页面:SessionJerry.jsp,参考代码如下:

    SessionJerry.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <p>我是Jerry页面<%String s = session.getId();%></p>
      <p>您在Jerry页面中的session对象的ID是:<%=s%><p>
      <p>点击超链接,连接到session的页面。 <br>
        <a href="SessionClient.jsp">欢迎到session屋来!</a>
      </p>
    </body>
    </html>
    
  4. 测试;访问http://localhost:8080/BuiltInTest/SessionClient.jsp,观察并记住当前sesson的id,分别点击TomJerry链接并观察session id的变化

application对象

创建三个JSP页面,实现如下功能:在留言板页面(ApplicationSubmit.jsp)中输入留言信息,提交至记录页面(ApplicationMessagePane.jsp),全局记录留言信息,然后在查看页面(ApplicationShowMessage.jsp)中查看记录信息,参考步骤如下:

  1. 创建留言板页面:ApplicationSubmit.jsp,用于在前端采集信息,参考代码如下:

    ApplicationSubmit.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <form action="ApplicationMessagePane.jsp" method="post" name="MessagePane">
        <p>输入您的名字: <input type="text" name="peopleName"><br></p>
        <p>输入您的留言标题: <input type="text" name="Title"><br></p>
        <p>输入您的留言:<br>
          <textarea name="messages" ROWs="10" COLS=36 WRAP="physical"></textarea>
          <br> 
          <input type="submit" value="提交信息" name="submit">
        </p>
      </form>
    
      <form action="ApplicationShowMessage.jsp" method="post" name="ShowMessage">
        <input type="submit" value="查看留言板" name="look">
      </form>
    </body>
    </html>
    
  2. 创建记录页面:ApplicationMessagePane.jsp,用于在application中记录前端采集的信息,参考代码如下:

    ApplicationMessagePane.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <%@ page import="java.util.*"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <%!
        Vector v = new Vector();
        int i = 0;
        ServletContext application;
    
        synchronized void sendMessage(String s) {
          application = getServletContext();
          i++;
          v.add("No." + i + "," + s);
          application.setAttribute("Mess", v);
        }
      %>
    
      <%
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("peopleName");
        String title = request.getParameter("Title");
        String messages = request.getParameter("messages");
        if (name == null) {
          name = "guest" + (int) (Math.random() * 10000);
        }
        if (title == null) {
          title = "无标题";
        }
        if (messages == null) {
          messages = "无信息";
        }
        String s = "Name:" + name + "#" + "Title:" + title + "#" + "Content:" + "#" + messages;
        sendMessage(s);
        out.print("您的信息已经提交!");
      %>
      <a href="ApplicationSubmit.jsp">返回</a>
    </body>
    </html>
    
  3. 创建查看页面:ApplicationShowMessage.jsp,用于查看application中存储的信息,参考代码如下:

    ApplicationShowMessage.jsp
    <%@ page contentType="text/html;charset=utf-8"%>
    <%@ page import="java.util.*"%>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
      <%
      Vector v = (Vector) application.getAttribute("Mess");
      for (int i = 0; i < v.size(); i++) {
        String message = (String) v.elementAt(i);
        out.print("<br>" + message);
      }
      %>
    </body>
    </html>
    
  4. 测试留言;在浏览器中访问http://localhost:8080/BuiltInTest/ApplicationSubmit.jsp,并在表单中填写信息并提交

  5. 查看留言;访问返回ApplicationSubmit.jsp页面,点击查看留言板,观察留言信息是否完整

综合

使用JSP实现学生表的增操作,用List在服务端存储数据,主要页面功能如下:

url 功能
/stu/init.jsp 初始化学生列表,成功后跳转到list.jsp
/stu/list.jsp 以表格显示学生列表,每行包含修改、删除链接
/stu/add_view.jsp 添加学生页面,成功后跳转到list.jsp
/stu/add.jsp 添加学生,成功后跳转到list.jsp
sequenceDiagram title JSP实现学生表增删改查操作流程 participant User participant InitJSP as /stu/init.jsp participant ListJSP as /stu/list.jsp participant AddViewJSP as /stu/add_view.jsp participant AddJSP as /stu/add.jsp User->>InitJSP: 访问初始化页面 InitJSP-->>ListJSP: 初始化学生列表后跳转 User->>ListJSP: 查看学生列表 User->>ListJSP: 点击添加链接 ListJSP-->>AddViewJSP: 跳转到添加页面 User->>AddViewJSP: 填写学生信息并提交 AddViewJSP-->>AddJSP: 传递学生信息 AddJSP-->>ListJSP: 添加成功后跳转 User->>ListJSP: 查看最终的学生列表
  1. 创建实体类:stu/Sutudent,封装学生信息,参考代码如下:

    stu.Student类
    package stu;
    
    /**
     * Class Student
     * 学生表
     * @author XUST
     * @version 1.0, 2023-04-20
     */
    public class Student{
        public Student() {
    
        }
    
        public Student(String no, String name, String gender, Integer age, String dept) {
            this.no = no;
            this.name = name;
            this.gender = gender;
            this.age = age;
            this.dept = dept;
        }   
    
        /**
         * 学号
         */
        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
        public String toString() {
        return "{" + "\"no\": " + "\"" + no + "\"" + ", " + "\"name\": " + "\"" + name + "\"" + ", " + "\"gender\": " + "\"" + gender + "\"" + ", " + "\"age\": " + age + ", " + "\"dept\": " + "\"" + dept + "\"" +  "}";
        }
    }
    
  2. 创建初始化页面:stu/init.jsp,初始化学生列表,参考代码如下:

    stu/init.jsp
    <%@ page import="stu.Student" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.List" %>
    <%@ page contentType="text/html;charset=utf-8" %>
    <%
      List<Student> students = new ArrayList<Student>();
      students.add(new Student("1", "张三", "男", 20, "计科"));
      students.add(new Student("2", "李四", "男", 20, "软工"));
      students.add(new Student("3", "王五", "男", 20, "网工"));
    
      session.setAttribute("stu_list", students);
    
      //初始化完成,回到列表
      response.sendRedirect(String.format("%s%s", request.getContextPath(), "/stu/list.jsp"));
    %>
    
  3. 创建列表页面:stu/list.jsp,显示学生列表,参考代码如下:

    stu/list.jsp
    <%@ page import="stu.Student" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.List" %>
    <%@ page contentType="text/html;charset=utf-8" %>
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>学生表</title>
    </head>
    
    <body>
      <h3>学生表</h3>
      <a href="<%=request.getContextPath()%>/stu/add_view.jsp">新增</a>
      <table id="STUDENT" border="1" width="100%">
        <thead>
          <th>学号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>年龄</th>
          <th>所在系</th>
          <th>操作</th>
        </thead>
        <tbody>
            <%
                    List<Student> students = (List<Student>)session.getAttribute("stu_list");
            if(students != null){
                for(Student stu: students){
                    String line = "";
                    line += String.format("<td>%s</td>", stu.getNo());
                    line += String.format("<td>%s</td>", stu.getName());
                    line += String.format("<td>%s</td>", stu.getGender());
                    line += String.format("<td>%s</td>", stu.getAge());
                    line += String.format("<td>%s</td>", stu.getDept());
                    line += String.format("<td><a href='%s/stu/update_view.jsp?no=%s'>修改</a>&nbsp;&nbsp;<a href='%s/stu/delete.jsp?no=%s'>删除</a></td>", request.getContextPath(), stu.getNo(), request.getContextPath(), stu.getNo());
                  out.print(String.format("<tr>%s</tr>", line));            
                }
            }
            %>
        </tbody>
      </table>
    </body>
    
    </html>
    
  4. 创建新建界面页面:stu/add_view.jsp,用于添加界面,参考代码如下:

    stu/add_view.jsp
    <%@ page contentType="text/html;charset=utf-8" %>
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>学生表</title>
    </head>
    
    <body>
      <h3>学生表</h3>
      <div>
        <form action="<%=String.format("%s/stu/add.jsp", request.getContextPath())%>">
          <div>
            <label for="no">学号:</label>
            <input type="text" id="no" name="no" placeholder="请输入学号..">
          </div>
          <div>
            <label for="name">姓名:</label>
            <input type="text" id="name" name="name" placeholder="请输入姓名..">
          </div>
          <div>
            <label for="gender">性别:</label>
            <input type="text" id="gender" name="gender" placeholder="请输入性别..">
          </div>
          <div>
            <label for="age">年龄:</label>
            <input type="number" id="age" name="age" placeholder="请输入年龄..">
          </div>
          <div>
            <label for="dept">所在系:</label>
            <input type="text" id="dept" name="dept" placeholder="请输入所在系..">
          </div>
          <button type="submit">提交</button>
        </form>
      </div>
    </body>
    
    </html>
    
  5. 创建新建页面:stu/add.jsp,实现添加功能,参考代码如下:

    stu/add.jsp
    <%@ page import="stu.Student" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.List" %>
    <%@ page contentType="text/html;charset=utf-8" %>
    <%
      Student stu_new = new Student();
    
      //获取表单数据
      stu_new.setNo(request.getParameter("no"));
      stu_new.setName(request.getParameter("name")); 
      stu_new.setGender(request.getParameter("gender")); 
      try{
        stu_new.setAge(Integer.parseInt(request.getParameter("age"))); 
      }catch(Exception e){
    
      }
      stu_new.setDept(request.getParameter("dept")); 
    
      List<Student> students = (List<Student>)session.getAttribute("stu_list");
      if(students != null){
        students.add(stu_new);
      }
    
      //操作完成,回到列表
      response.sendRedirect(String.format("%s%s", request.getContextPath(), "/stu/list.jsp"));
    %>
    

拓展练习

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