跳至主要內容

JSP基础语法

wangdx大约 17 分钟

JSP 注释

> JSP 支持两类注释:

> 显式注释: <!--注释内容 -->、HTML 注释
隐式注释
  >Java 注释
    > 单行注释://
    > 多行注释:/_..._/
    > 文档注释:/\*\*
  > JSP 注释:<%--JSP 注释--%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%-- 【HTML注释】HTML Comment --%>
<%	// 【Java单行注释】这部分的注释内容是不会发送到客户端中的
    /*
    * 【多行注释】所有的注释信息只能够在服务器端程序上访问
    * 本次讲解的全套的JavaWEB是基于JavaEE9.0标准讲解的,所以属于最新版本的课程内容
    * */
    out.println("<h1>www.yootk.com</h1>");
%>
</body>
</html>

<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%-- 【快捷键:CTRL + /】这属于JSP的注释,为隐式注释,不会发送到客户端浏览器上 --%>
<%	// 【Java单行注释】这部分的注释内容是不会发送到客户端中的
    /*
    * 【多行注释】所有的注释信息只能够在服务器端程序上访问
    * 本次讲解的全套的JavaWEB是基于JavaEE9.0标准讲解的,所以属于最新版本的课程内容
    * */
    out.println("<h1>www.yootk.com</h1>");
%>
</body>
</html>

Scriptlet 简介

Scriptlet(脚本小程序)实现 HTML 与 Java 代码分离

Scriptlet 结构分为三种形式:代码编写 Scriptlet、结构定义 Scriptlet、表达式输出 Scriptlet;

代码编写 Scriptlet

代码编写 Scriptlet

JSP 中为了实现动态生成页面的需求,会编写大量的 Java 程序语句以及相应的局部变量,这样就可以在代码编写 Scriptlet 中进行编写。

1、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%	// 与HTML代码的区分主要依靠此标记
    out.println("<table border='1'>"); // 输出HTML元素
    for (int x = 1 ; x <= 9 ; x ++) {   // 外层循环
        out.println("<tr>"); // 输出表格行
        for (int y = 1; y <= x; y ++) { // 输出表格列
            out.println("<td>" + x + " * " + y + " = " + (x * y) +"</td>");
        }
        for (int y = 0 ; y < 9 - x; y ++) {
            out.println("<td>&nbsp;</td>");
        }
        out.println("</tr>"); // 输出表格行
    }
    out.println("</table>");
%>
</body>
</html>

2、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%	// 与HTML代码的区分主要依靠此标记
    String message = "yootk";
    switch(message) {
        case "yootk":
            out.println("<h1>www.yootk.com</h1>");
            break;
        case "muyan":
            out.println("<h1>沐言科技</h1>");
        case "happy":
            out.println("<h1>爆可爱的小李老师</h1>");
    }
%>
</body>
</html>

3、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%	// 与HTML代码的区分主要依靠此标记
    StringBuffer buf = new StringBuffer();
    buf.append("www").append(".").append("yootk.com"); // 字符串连接
    out.println("<h1>" + buf + "</h1>");
%>
</body>
</html>

结构定义 Scriptlet

JSP 程序中可以利用结构定义 Scriptlet 代码块实现全局变量、全局常量、类以及操作方法的定义,这样就可以在代码编写 Scriptlet 中进行调用

1、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 结构定义Scriptlet,是在类中进行的内容定义
    int count = 0; // 全局变量
%>
<%  // 代码编写Scriptlet,相当于在方法中进行的代码定义
    int number = 100; // 局部变量
%>
<%	// 尽管在一个JSP文件中可以有多个不同的代码编写Scriptlet,但是这些Scriptlet都存在有关联
    out.println("<h1>count = " + (count ++) + "</h1>");
    out.println("<h1>number = " + (number ++) + "</h1>");
%>
</body>
</html>

2、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 结构定义Scriptlet,是在类中进行的内容定义
    public static final String MESSAGE = "www.yoootk.com"; // 全局常量
%>
<%	// 尽管在一个JSP文件中可以有多个不同的代码编写Scriptlet,但是这些Scriptlet都存在有关联
    out.println("<h1>" + MESSAGE + "</h1>");
%>
</body>
</html>

3、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 结构定义Scriptlet,是在类中进行的内容定义
    public int sum(int ... args) {  // 可变参数
        int all = 0; // 保存累加结果
        for (int temp : args) {
            all += temp; // 实现累加
        }
        return all;
    }
%>
<%	// 尽管在一个JSP文件中可以有多个不同的代码编写Scriptlet,但是这些Scriptlet都存在有关联
    out.println("<h1>" + sum(1, 2, 3, 4, 5, 6, 7, 8) + "</h1>");
%>
</body>
</html>

4、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 结构定义Scriptlet,是在类中进行的内容定义
    class Book {    //. 图书类
        private String title;
        private String author;
        private double price;
        public Book(String title, String author, double price) {
            this.title = title;
            this.author = author;
            this.price = price;
        }
        @Override
        public String toString() {
            return "title = " + this.title + "、author = " + this.author + "、price = price";
        }
    }
%>
<%	// 尽管在一个JSP文件中可以有多个不同的代码编写Scriptlet,但是这些Scriptlet都存在有关联
    out.println("<h1>" + new Book("Java", "Small.Lee", 99.8) + "</h1>");
%>
</body>
</html>

表达式输出 Scriptlet

由于 JSP 程序需要进行大量程序计算结果的输出,为了便于数据输出显示,提供了表达式输出 Scriptlet 结构,利用该结构可以方便的实现变量与常量内容的输出。

1、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 结构定义Scriptlet,是在类中进行的内容定义
    class Book {    //. 图书类
        private String title;
        private String author;
        private double price;
        public Book(String title, String author, double price) {
            this.title = title;
            this.author = author;
            this.price = price;
        }
        @Override
        public String toString() {
            return "title = " + this.title + ", author = " + this.author + ", price = price";
        }
    }
%>
<%	// 尽管在一个JSP文件中可以有多个不同的代码编写Scriptlet,但是这些Scriptlet都存在有关联
    out.println("<h1>" + new Book("Java", "Small.Lee", 99.8) + "</h1>");
%>
<h1><%=new Book("Java", "Small.Lee", 99.8)%></h1>
</body>
</html>

2、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<table border="1">
<%
    for (int x = 1; x <= 9; x ++) {
%>
    <tr>
<%
        for (int y = 1 ; y <= x; y ++) {
%>
        <td><%=x%> * <%=y%> = <%=x * y%></td>
<%
        }
        for (int y = 1 ; y <= 9 - x; y ++) {
%>
        <td>&nbsp;</td>
<%
        }
%>
    </tr>
<%
    }
%>
</table>
</body>
</html>

3、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "www.yootk.com";
%>
<h1><%=MESSAGE%></h1>
<h1><%="Hello EveryOne"%></h1>
</body>
</html>

Scriptlet 标签指令

在 JSP 程序开发中,需要通过“代码编写 Scriptlet”编写大量的程序代码,有时候为了满足一个业务需求,往往在程序中也需要编写多个“<%%>”代码,为了美化 JSP 页面的代码编写结构,可以使用“<jsp:scriptlet>”标签形式来代替。

<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    int count = 0; // 全局变量,类中的成员属性
%>
<jsp:scriptlet>
    int number = 100; // 局部变量
</jsp:scriptlet>
<h1>count = <%=count++%></h1>
<h1>number = <%=number++%></h1>
</body>
</html>

page 指令

page 指令主要定义了一个 JSP 页面中的相关属性内容,例如 import 导入系统包、MIME 配置、错误页、IO 缓冲区配置等其使用格式为: <%@ page 属性名称 1=属性内容 1 属性名称 2=属性内容 2 ...%>

页面编码

JSP 页面最终执行后都会以 HTML 文件格式发送到客户端浏览器>如果在生成 HTML 代码时存在有中文,并且没有进行相应的编码配置,那么此时在浏览器上所显示的就会是乱码,如果要想解决乱码就可以通过“pageEncoding”属性配置,而常见的编码为“UTF-8”

1、
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

2、
<%@ page pageEncoding="UTF-8" %>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

3、
<%@ page pageEncoding="UTF-8" %>    <%-- 设置页面的显示编码 --%>
<%@ page pageEncoding="GBK" %>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

MIME

MIME(Multipurpose Internet Mail Extensions、多用途瓦联网邮件扩展类型)是一种根据文件扩展名匹配相关应用程序的标识,例如:当用户获取到了一个 pdf 文件并打开时,会自动匹配本机的 PDF 阅读器,这依靠的就是 MIME 配置实现的在 page 指令中可以通过“contentType”属性来实现 MIME 类型的定义。

范例:设置 MIME 类型为 HTME><%@page contentType="text/html; charset=UTF-8" %>

1、
<%@ page pageEncoding="UTF-8" contentType="text/html" %>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

2、
    <mime-mapping>
        <extension>xml</extension>
        <mime-type>application/xml</mime-type>
    </mime-mapping>


3、
<%@ page pageEncoding="UTF-8" contentType="application/xml; charset=UTF-8" %>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

4、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<%@ page contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document"%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%!
    public static final String MESSAGE = "沐言科技:www.yootk.com"; // 全局常量
%>
<h1><%=MESSAGE%></h1>
</body>
</html>

错误页

默认错误处理

在 JSP 程序运行中如果程序处理不当,则一般都有可能产生异常,如果在某一个 JSP 页面没有进行异常处理,则该页面会直接将所有的异常信息打印在页面上,这样是非常不安全的,同时也不利于用户的使用

自定义错误页

最佳的做法是不管有多少个页面出现错误,都可以统一跳转到一个页面中进行错误显示,这样就可以由开发者自己来决定错误信息的显示内容,便于用户使用。

详情
1、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%=10/0%>
</body>
</html>

2、
<%@ page pageEncoding="UTF-8" isErrorPage="true" %>    <%-- 这是一个错误显示页 --%>
<html>
<head>
    <title>【错误页】沐言科技:www.yootk.com</title>
</head>
<body>
<h1>【骚蕊】对不起,由于你的幸运,我们出错了!</h1>
<img src="images/wrong.png">
<img src="images/logo.png" style="height: 120px;">
<hr><%=exception%>  <%-- exception描述了异常信息 --%>
</body>
</html>

5、
<%@ page pageEncoding="UTF-8" errorPage="errors.jsp" %> <%-- 设置错误处理页 --%>
<html>
<head>
    <title>【程序页】沐言科技:www.yootk.com</title>
</head>
<body>
计算结果:<%=10 / 0%>
</body>
</html>

6、
<%@ page pageEncoding="UTF-8"%> <%-- 设置错误处理页 --%>
<html>
<head>
    <title>【程序页】沐言科技:www.yootk.com</title>
</head>
<body>
计算结果:<%=10 / 0%>
</body>
</html>

7、 修改web.xml
    <error-page>    <!-- 全局错误页配置,所有的页面只要出错都会自动匹配 -->
        <error-code>404</error-code>    <!-- HTTP状态码匹配 -->
        <location>/errors.jsp</location>    <!-- 错误显示页 -->
    </error-page>
    <error-page>    <!-- 全局错误页配置,所有的页面只要出错都会自动匹配 -->
        <error-code>500</error-code>    <!-- HTTP状态码匹配 -->
        <location>/errors.jsp</location>    <!-- 错误显示页 -->
    </error-page>
    <error-page>    <!-- 全局错误页配置,所有的页面只要出错都会自动匹配 -->
        <exception-type>java.lang.Exception</exception-type>    <!-- 异常匹配 -->
        <location>/errors.jsp</location>    <!-- 错误显示页 -->
    </error-page>


import

项目开发中会经常性的使用到其他包中的程序类,此时就可以利用 page 指令中的 import 属性实现开发包的导入操作,在使用 import 时可以单独导入一个包,也可以同时导入多个开发包如下格式所示:

导入一个包:<%@page import="开发包"%>>

导入多个包:<%@page import=“开发包 1,开发包 2,开发包 3"%>>多个开发包中间使用“"分割

<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<%@ page import="java.time.*,java.util.*" %>    <%-- 多个包之间使用“,”分割 --%>
<%@ page import="java.time.format.*" %>
<html>
<head>
    <title>沐言科技:www.yootk.com</title>
</head>
<body>
<%! // 定义一个全局的日期格式化格式
    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
%>
<%
    List<String> all = List.of("2006-10-10 21:21:21", "2008-08-08 20:08:08"); // 创建List集合
    for (String str : all) {    // foreach迭代
        try {
            LocalDateTime dateTime = LocalDateTime.parse(str, FORMATTER);
            ZoneId zoneId = ZoneId.systemDefault(); // 获取时区
            Instant instant = dateTime.atZone(zoneId).toInstant();
            Date date = Date.from(instant);
%>
            <h1>字符串转日期:<%=date%></h1>
<%
        } catch (Exception e) {}
    }
%>
</body>
</html>

MySQL 数据加载

动态 WEB 程序运行在 WEB 容器之中,利用 WEB 容器就可以使用 JDBC 技术实现数据库数据的 CRUD 操作,将数据表中的数据取出并结合 JSP 动态生成 HTML 界面进行显示

1、

DROP DATABASE IF EXISTS yootk ;
CREATE DATABASE yootk CHARACTER SET UTF8 ;
USE yootk ;
CREATE TABLE dept (
   deptno    BIGINT    AUTO_INCREMENT ,
   dname     VARCHAR(50) ,
   loc       VARCHAR(50) ,
   CONSTRAINT pk_deptno PRIMARY KEY(deptno)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 开发部', '成都') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 教学部', '北京') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 财务部', '上海') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 市场部', '深圳') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 后勤部', '洛阳') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 公关部', '广州') ;
COMMIT;

2、
<%@ page pageEncoding="UTF-8"%> <%-- 设置错误处理页 --%>
<%@ page import="java.sql.*" %> <%-- JDBC程序包 --%>
<html>
<head>
    <title>沐言科技:www.yootk.com</title>
</head>
<body>
<%!
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String DBURL = "jdbc:mysql://localhost:3306/yootk";
    public static final String USER = "root";
    public static final String PASSWORD = "root";
%>
<%
    String sql = "SELECT deptno,dname,loc FROM dept";
    Class.forName(DBDRIVER); // 加载驱动
    Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD); // 连接数据库
    PreparedStatement pstmt = conn.prepareStatement(sql); // 创建数据库操作对象
    ResultSet rs = pstmt.executeQuery();
%>
<table border="1" width="100%">
    <thead><tr><td>部门编号</td><td>部门名称</td><td>部门位置</td></tr></thead>
    <tbody>
<%
    while (rs.next()) { // 迭代结果集
        long deptno = rs.getLong(1);
        String dname = rs.getString(2);
        String loc = rs.getString(3);
%>
    <tr>
        <td><%=deptno%></td>
        <td><%=dname%></td>
        <td><%=loc%></td>
    </tr>
<%
    }
    conn.close(); // 在WEB中如果没有关闭数据库连接,就再也关不上了,除非重新启动服务器
%>
    </tbody>
</table>
</body>
</html>

JavaBean 定义与使用

JavaBean

为了提高 Java 程序代码的可重用性,往往会将一些重复执行的代码封装在类结构之中,而这样的类也被称为 JavaBean。

1、
package com.yootk.dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {   // 数据库连接管理类
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String DBURL = "jdbc:mysql://localhost:3306/yootk";
    public static final String USER = "root";
    public static final String PASSWORD = "mysqladmin";
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    private DatabaseConnection() {} // 构造方法私有化
    public static Connection rebuildConnection() {  // 重新创建数据库连接
        Connection conn = null ;
        try {
            Class.forName(DBDRIVER);
            conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
        } catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }
    public static Connection getConnection() {
        Connection conn = THREAD_LOCAL.get(); // 获取当前线程中的连接对象
        if (conn == null) { // 没有连接对象
            conn = rebuildConnection(); // 建立数据库连接
            THREAD_LOCAL.set(conn); // 保存连接对象
        }
        return conn;
    }
    public static void close() {
        Connection conn = THREAD_LOCAL.get(); // 获取当前线程中的连接对象
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            THREAD_LOCAL.remove(); // 清空ThreadLocal
        }
    }
}

2、
<%@ page pageEncoding="UTF-8"%> <%-- 设置错误处理页 --%>
<%@ page import="java.sql.*" %> <%-- JDBC程序包 --%>
<%@ page import="com.yootk.dbc.*" %>    <%-- 导入自定义程序包 --%>
<html>
<head>
    <title>沐言科技:www.yootk.com</title>
</head>
<body>
<%
    String sql = "SELECT deptno,dname,loc FROM dept";
    PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();
%>
<table border="1" width="100%">
    <thead><tr><td>部门编号</td><td>部门名称</td><td>部门位置</td></tr></thead>
    <tbody>
<%
    while (rs.next()) { // 迭代结果集
        long deptno = rs.getLong(1);
        String dname = rs.getString(2);
        String loc = rs.getString(3);
%>
    <tr>
        <td><%=deptno%></td>
        <td><%=dname%></td>
        <td><%=loc%></td>
    </tr>
<%
    }
    DatabaseConnection.close();
%>
    </tbody>
</table>
</body>
</html>

include 简介

页面展示结构

为了便于程序的功能结构的统一,往往需要对一个页面的组成结构进行分割,同时会在不同的页面中出现相同的程序代码

页面导入组合

在不同的页面中会存在有相同功能的程序代码,可以将“头部代码”“尾部代码”以及“工具栏”分别定义在不同的程序文件中,在需要处进行导入

静态导入

静态导入操作是在程序代码导入处设置一个标记环境,而后在代码执行时将导入的代码直接进行替换,最终合并为一个文件进行处理,静态导入语法:

<%@ include file="要包含的文件路径"%>

1、<%@ include file="要包含的文件路径"%>

2、<h1>part.html</h1>

3、<h1>part.inc</h1>

4、
<%
    String message = "www.yootk.com";
%>
<h1><%=message%></h1>

5、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%@ include file="part.html" %>
<%@ include file="part.inc" %>
<%@ include file="part.jsp" %>
</body>
</html>

6、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<h1>part.html</h1>
<h1>part.inc</h1>
<%
    String message = "www.yootk.com";
%>
<h1><%=message%></h1>
</body>
</html>


动态导入

动态导入

使用静态导入进行并不会关心具体的文件类型,而是将程序代码全部合并在一起后再进行处理,而除了此类导入之外,在 JSP 中又提供了一个动态导入操作,该导入功能最大的特点是可以区分被导入的页面是动态文件还是静态文件,如果是静态文件则功能与静态导入相同,如果是动态文件,则先进行动态页面的处理,然后再将结果包含进来

动态导入语法

- 形式一:导入页面时不传递任何参数>
  - <jsp:include page="导入文件路径"/>
- 形式二:导入页面同时传递参数>
  - <jsp:include page="导入文件路径">
      <jsp:param name="参数名称" value="参数内容"/>
      <jsp:param name="参数名称"value="参数内容"/>
      .....
    </jsp:include>
1、
	<jsp:include page="导入文件路径"/>

2、
<jsp:include page="导入文件路径">
	<jsp:param name="参数名称" value="参数内容"/>
	<jsp:param name="参数名称" value="参数内容"/>
	<jsp:param name="参数名称" value="参数内容"/>
		... ... 多少个参数都是可以传递的
</jsp:include>

3、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<jsp:include page="part.html"/><%--<%@ include file="part.html" %>--%>
<jsp:include page="part.inc"/><%--<%@ include file="part.inc" %>--%>
<jsp:include page="part.jsp"/><%--<%@ include file="part.jsp" %>--%>
</body>
</html>

4、
<%@ page pageEncoding="UTF-8" %>
<%  // 接收请求参数
    String title = request.getParameter("title"); // 传递的参数
    String url = request.getParameter("url"); // 传递的参数
%>
<h1>【参数接收】<%=title%>:<%=url%></h1>

5、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%! // 定义全局常量
    public static final String URL = "www.yootk.com"; // 常量
%>
<%-- 传递的是一个字符串的信息 --%>
<%-- 变量内容通过表达式输出 --%>
<jsp:include page="param.jsp">
    <jsp:param name="title" value="沐言科技"/>
    <jsp:param name="url" value="<%=URL%>"/>
</jsp:include>
</body>
</html>

静态导入与动态导入

区别通过之前的分析可以发现,不管是动态包含还是静态包含,在实现静态文件包含时功能相同,而在实现动态文件包含时,两者的处理机制会有所不同:

  • 静态包含:采用先包含后处理的形式,即将所需要的代码先包含到程序之中,而后一起解析;
  • 动态包含:采用先处理后包含的形式,即不包含程序的源代码,只是包含程序的执行结果。
1、
<%@ page pageEncoding="UTF-8" %>    <%-- 每个页面都有此代码 --%>
<%
    int num = 30; // 定义局部变量
%>
<h1>【info.jsp页面】num = <%=num%></h1>

2、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%  // info.jsp中也存在有一个num变量
    int num = 100; // 你没有看错,同样也是num变量
%>
<h1>【include.jsp页面】num = <%=num%></>
<%@ include file="info.jsp"%>   <%-- 静态导入 --%>
</body>
</html>

3、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%  // info.jsp中也存在有一个num变量
    int num = 100; // 你没有看错,同样也是num变量
%>
<h1>【include.jsp页面】num = <%=num%></>
<jsp:include page="info.jsp"/>  <%-- 动态导入 --%>
</body>
</html>

跳转指令

为了便于代码的管理,往往会按照不同的功能创建所需要的 JSP 页面,而后当某些程序逻辑处理完成后,希望其可以根据结果跳转到不同的页面进行显示,这样就需要使用到 forward 跳转指令,该指令为标签指令形式,提供有如下两类操作形式:

形式一:导入页面时不传递任何参数
  <jsp:forward page="目标文件路径"/>
形式二:导入页面同时传递参数
  <jsp:forward page="目标文件路径">
    <jsp:param name="参数名称" value="参数内容"/>
    <jsp:param name="参数名称" value="参数内容"/>
  </jsp:forward>
1、
<jsp:forward page="跳转目标页面"/>

2、
<jsp:forward page="跳转目标页面">
	<jsp:param name="参数名称" value="参数内容"/>
	<jsp:param name="参数名称" value="参数内容"/>
		... ...
</jsp:forward>

3、
<%@ page pageEncoding="UTF-8" %>
<%  // 接收请求参数
    String title = request.getParameter("title"); // 传递的参数
    String url = request.getParameter("url"); // 传递的参数
%>
<h1>【参数接收】<%=title%>:<%=url%></h1>

4、
<%@ page pageEncoding="UTF-8"%>    <%-- 设置页面的显示编码 --%>
<html>
<head>
    <title>www.yootk.com</title>
</head>
<body>
<%  // 代码编写Scriptlet
    String message = "www.yootk.com"; // 一个字符串对象
    if (message.contains("yootk")) {    // 字符串查找
%>
        <jsp:forward page="param.jsp">
            <jsp:param name="title" value="沐言科技"/>
            <jsp:param name="url" value="<%=message%>"/>
        </jsp:forward>
<%
    } else {    // 不能够发现
%>
        <h1>口令错误,不允许进入系统!</h1>
<%
    }
%>
</html>

5、
http://localhost/forward.jsp

项目案例

JSP 开发中需要融合 HTML/CSS/JavaScript 等基础的前端开发技术,为了帮助读者快速的建立起 WEB 开发的核心概念,在本次课程中将实现一个用户登录处理操作

代码地址open in new window

上次编辑于: