JSP 高级教程学习笔记

一、JSP 自定义标签库

1.1 定义标签库描述符文件

WEB-INF 目录下新建 tld 目录,然后再创建一个 .tld 文件。例如:mytags.tld

xmlCopy Code
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>mytags</short-name> <uri>http://www.example.com/tags/mytags</uri> <tag> <name>hello</name> <tag-class>com.example.tags.HelloTag</tag-class> <body-content>empty</body-content> <attribute> <name>name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>

1.2 编写 Java 类

WEB-INF/classes 目录下创建对应的包及 Java 类,例如:com.example.tags.HelloTag

javaCopy Code
package com.example.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag extends SimpleTagSupport { private String name; public void setName(String name) { this.name = name; } public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.print("Hello, " + name); } }

1.3 在 JSP 页面中使用标签库

在 JSP 页面中引入标签库,并使用自定义标签

jspCopy Code
<%@ taglib uri="http://www.example.com/tags/mytags" prefix="my" %> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello Tag</title> </head> <body> <my:hello name="Jerry" /> </body> </html>

二、JSP 中的 EL 表达式

2.1 对象的获取和设置

可以使用 EL 表达式获取或者设置 JSP 中的对象属性值,例如:

jspCopy Code
${pageScope.name} <!-- 获取 pageScope 中的 name 属性 --> ${sessionScope.count} <!-- 获取 sessionScope 中的 count 属性 --> ${param.username} <!-- 获取请求参数中的 username 参数值 --> ${requestScope.message} <!-- 获取 requestScope 中的 message 属性 -->

2.2 运算符

EL 表达式支持多种运算符,包括算术运算符、比较运算符、逻辑运算符等。

jspCopy Code
${2+3} <!-- 加法运算 --> ${3>2} <!-- 比较运算 --> ${true and false} <!-- 逻辑运算 -->

2.3 条件语句

EL 表达式也支持条件语句,例如:

jspCopy Code
${empty user.name ? 'Guest' : user.name} <!-- 如果 user.name 为空,则返回 'Guest',否则返回 user.name -->

三、JSP 中的 JSTL 标签库

3.1 引入 JSTL

在 JSP 页面中引入 JSTL:

jspCopy Code
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

3.2 JSTL 标签

JSTL 提供了多种标签,包括条件标签、迭代标签等。例如:

jspCopy Code
<c:if test="${empty user}"> <p>Welcome, guest</p> </c:if> <c:forEach var="item" items="${books}"> <li>${item}</li> </c:forEach>

四、JSP 中的 MVC 架构

4.1 控制器(Servlet)

控制器负责处理用户请求,并使用 JSP 视图实现响应页面。例如:

javaCopy Code
@WebServlet("/hello") public class HelloController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); request.setAttribute("name", name); request.getRequestDispatcher("/hello.jsp").forward(request, response); } }

4.2 视图(JSP)

JSP 视图用来展示数据。例如:

jspCopy Code
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello JSP</title> </head> <body> <h1>Hello, ${name}</h1> </body> </html>

4.3 模型(Java Bean)

模型用来封装业务逻辑和数据访问。例如:

javaCopy Code
public class User { private String name; private int age; // getters and setters }