做移動網(wǎng)站快速排名軟件seo變現(xiàn)培訓
1 JSP注釋
1.1 顯示注釋
顯示注釋會出現(xiàn)在生成的HTML文檔中,對用戶可見。
<!-- 這是一個HTML顯示注釋 -->
1.2 隱式注釋
隱式注釋不會出現(xiàn)在生成的HTML文檔中,對用戶不可見。
<%-- 這是一個JSP隱式注釋 --%>
2 JSP腳本元素
2.1 局部變量和語句
使用<% %>
編寫局部變量和語句。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><title>JSP腳本元素</title> </head> <body><%String message = "歡迎來到JSP世界!";%><h1><%= message %></h1> </body> </html>
2.2 全局變量、方法和類
使用<%! %>
聲明全局變量、方法和類。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><title>JSP腳本元素</title> </head> <body><%!public String getMessage() {return "歡迎來到JSP世界!";}%><h1><%= getMessage() %></h1> </body> </html>
2.3 表達式
使用<%= %>
輸出表達式的值。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><title>JSP腳本元素</title> </head> <body><h1>當前時間:<%= new java.util.Date() %></h1> </body> </html>
2.4 JSP Include
<jsp:include>
動作用于動態(tài)包含另一個JSP頁面的內(nèi)容。這對于避免重復代碼非常有用,例如在多個頁面中包含相同的頭部和尾部內(nèi)容。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><title>JSP Include</title> </head> <body><jsp:include page="header.jsp" /><p>這是主頁面的內(nèi)容。</p><jsp:include page="footer.jsp" /> </body> </html>
3 動態(tài)包含
動態(tài)包含是指在一個JSP頁面中動態(tài)地包含另一個JSP頁面的內(nèi)容。這種包含方式是動態(tài)的,因為被包含的頁面只有在請求到來時才會被加載。
3.1 特點
-
包含與被包含的頁面是獨立的,它們各自有自己的生命周期和作用域。
-
可以出現(xiàn)同名變量。由于每個頁面都有自己的作用域,因此即使變量名相同,也不會發(fā)生沖突。
-
動態(tài)包含可以傳遞參數(shù),這使得被包含的頁面可以根據(jù)傳遞的參數(shù)動態(tài)地生成內(nèi)容。
3.2 示例
假設我們有兩個JSP頁面:main.jsp
和 included.jsp
。
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dynamic Include Example</title> </head> <body><h1>Main Page</h1><jsp:include page="included.jsp" /> </body> </html>
included.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <h2>Included Page</h2>
在這個例子中,當用戶訪問 main.jsp
時,服務器會動態(tài)地包含 included.jsp
的內(nèi)容。
4 四大作用域
在JSP中,有四種不同類型的作用域,它們決定了變量的生命周期和可見性。
4.1 Page作用域
-
生命周期:僅限于當前頁面。
-
可見性:只在當前頁面內(nèi)可見。
-
當頁面跳轉時,Page作用域內(nèi)的變量將失效。
4.2 Request作用域
-
生命周期:一次HTTP請求。
-
可見性:在整個請求處理過程中可見,包括轉發(fā)和包含操作。
-
超鏈接跳轉后,Request作用域內(nèi)的變量仍然有效。
4.3 Session作用域
-
生命周期:一次用戶會話。
-
可見性:在整個用戶會話期間可見。
-
當用戶關閉瀏覽器或會話超時后,Session作用域內(nèi)的變量將失效。
4.4 Application作用域
-
生命周期:整個Web應用程序的生命周期。
-
可見性:在整個Web應用程序中可見。
-
只有在應用程序重啟后,Application作用域內(nèi)的變量才會失效。
4.5 示例代碼
使用不同作用域的變量
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Scope Example</title> </head> <body><% // Page作用域的變量String pageVar = "This is a page scope variable.";// Request作用域的變量request.setAttribute("requestVar", "This is a request scope variable.");// Session作用域的變量session.setAttribute("sessionVar", "This is a session scope variable.");// Application作用域的變量application.setAttribute("applicationVar", "This is an application scope variable.");%><h1>Page Scope Variable:</h1><%= pageVar %><h1>Request Scope Variable:</h1><%= request.getAttribute("requestVar") %><h1>Session Scope Variable:</h1><%= session.getAttribute("sessionVar") %><h1>Application Scope Variable:</h1><%= application.getAttribute("applicationVar") %> </body> </html> ?
5 案例代碼
5.1 編寫代碼
5.1.1 后端驗證
創(chuàng)建一個簡單的用戶類User.java
:
public class User {private String username;private String password; ?public User(String username, String password) {this.username = username;this.password = password;} ?public String getUsername() {return username;} ?public String getPassword() {return password;} }
創(chuàng)建一個ServletLoginServlet.java
來處理登錄請求:
import javax.servlet.*; import javax.servlet.http.*; import java.io.IOException; ? public class LoginServlet extends HttpServlet {private User user = new User("admin", "password"); // 模擬用戶數(shù)據(jù) ?protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username = request.getParameter("username");String password = request.getParameter("password"); ?if (user.getUsername().equals(username) && user.getPassword().equals(password)) {HttpSession session = request.getSession();session.setAttribute("user", username);response.sendRedirect("index.jsp");} else {response.sendRedirect("login.jsp?error=true");}} }
5.1.2 前端登錄頁面
創(chuàng)建一個HTML文件login.html
作為登錄頁面:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Login</title> </head> <body><h1>Login</h1><form action="LoginServlet" method="post"><label for="username">Username:</label><input type="text" id="username" name="username" required><br><label for="password">Password:</label><input type="password" id="password" name="password" required><br><input type="submit" value="Login"></form><% if (request.getParameter("error") != null) { %><p style="color: red;">Invalid username or password.</p><% } %> </body> </html>
5.1.3 首頁顯示用戶名
創(chuàng)建一個JSP文件index.jsp
作為首頁:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><meta charset="UTF-8"><title>Index</title> </head> <body><h1>Welcome to the Index Page</h1><% if (session.getAttribute("user") != null) { %><p>Hello, <%= session.getAttribute("user") %>!</p><% } else { %><p>Please login first.</p><% } %><a href="login.html">Login</a> </body> </html>
5.1.4 配置Web應用程序
-
在
web.xml
文件中配置LoginServlet
:
<web-app><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/LoginServlet</url-pattern></servlet-mapping> </web-app>
-
將
login.html
、index.jsp
、User.java
和LoginServlet.java
文件放置在正確的目錄下。
6 EL表達式(Expression Language)
EL表達式是JSP的一部分,用于簡化數(shù)據(jù)訪問和操作。它允許開發(fā)者在JSP頁面中直接訪問JavaBean屬性、集合元素以及請求作用域屬性。
6.1 EL表達式的基本用法
-
使用
${}
來包裹要訪問的變量或屬性。 -
EL表達式默認從
pageScope
開始查找屬性,如果沒有找到,會繼續(xù)查找requestScope
、sessionScope
和applicationScope
。 -
如果找不到對應的屬性,EL表達式會返回空字符串(而不是拋出異常)。
6.2 EL表達式獲取值
-
List:通過索引訪問列表元素,如
${list[0]}
。也可以使用${list.size()}
來獲取列表的大小(但注意這不是EL標準用法,應使用JSTL的<c:forEach>
配合varStatus
屬性)。 -
Map:通過鍵訪問映射元素,如
${map.key}
。 -
JavaBean:通過屬性名訪問JavaBean屬性,如
${bean.propertyName}
。
7 JSTL(JavaServer Pages Standard Tag Library)
JSTL是一組標準的JSP標簽庫,用于簡化JSP頁面的開發(fā)。
7.1 核心標簽庫
-
條件判斷:
<c:if>
標簽用于條件判斷,但沒有else
部分。 -
循環(huán):
<c:forEach>
標簽用于遍歷集合。
7.2 格式化標簽庫
-
格式化日期:
<fmt:formatDate>
標簽用于格式化日期。
7.3 使用taglib引入標簽庫
-
使用
<%@ taglib %>
指令引入標簽庫,并通過prefix
屬性指定前綴。
7.4 案例代碼
7.4.1 EL表達式示例
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head><title>EL Expression Example</title> </head> <body><%// 設置作用域屬性pageContext.setAttribute("name", "Alice");request.setAttribute("city", "New York");session.setAttribute("country", "USA");application.setAttribute("hobby", "Reading");%><p>Name: ${name}</p><p>City: ${city}</p><p>Country: ${country}</p><p>Hobby: ${hobby}</p> </body> </html>
7.4.2 JSTL核心標簽庫示例
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head><title>JSTL Core Tags Example</title> </head> <body><%// 設置作用域屬性request.setAttribute("numbers", Arrays.asList(1, 2, 3, 4, 5));%><c:if test="${not empty numbers}"><ul><c:forEach items="${numbers}" var="num"><li>${num}</li></c:forEach></ul></c:if> </body> </html>
7.4.3 JSTL格式化標簽庫示例
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head><title>JSTL Format Tags Example</title> </head> <body><%Date now = new Date();pageContext.setAttribute("now", now);%><fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss" /> </body> </html>