-
JavaBeans
:符合某種規定的規范的java類。使用javabeans的好處是解決代碼重復編寫
,減少代碼冗余
,功能區分明確
,提高了代碼的維護性
。 - JavaBeans的設計原則:
公有類
,無參的公有構造方法
,私有屬性
,getter和setter方法
。 -
JSP動作元素
(action elements):動作元素為請求處理階段提供信息。動作元素遵循XML元素的語法,有一個包含元素名的開始標簽,可以有屬性、可選的內容、與開始標簽匹配的結束標簽。共有五大類元素:
- 第一類是與存取JavaBean有關的,包括
<jsp:useBean>
、<jsp:setProperty>
、<jsp:getProperty>
- 第二類是JSP1.2就開始有的基本元素,包括6個動作元素:
<jsp:include>
、<jsp:forward>
、<jsp:param>
、<jsp:plugin>
、<jsp:params>
、<jsp:fallback>
- 第三類是JSP2.0新增的動作元素,主要與JSP Document有關,包括六個元素:
<jsp:root>
、<jsp:declaration>
、<jsp:scriptlet>
、<jsp:expression>
、<jsp:text>
、<jsp:output>
- 第四類是JSP2.0新增的動作元素,主要用來動態生成XML元素標簽的值,包括3個動作:
<jsp:attribute>
、<jsp:body>
、<jsp:element>
- 第五類是JSP2.0 新增的動作元素,主要用在
Tag File
中,有2個元素:<jsp:invoke>
、<jsp:dobody>
- 在jsp頁面中通常使用jsp動作標簽來使用javabean。
-
<jsp:useBean>
的作用:在jsp頁面中實例化或者在指定范圍內使用javabean:
<jsp:useBean id="標示符" class="java包名+類名" scope="作用范圍" />
-
<jsp:setProperty>
的作用:給已實例化的javabean對象的屬性賦值
,一共有4種形式:
<jsp:setProperty name="javaBean實例名" property="*" />(跟表單關聯,'*'表示根據表單中的參數和javaBean中的屬性名進行一一匹配,若匹配成功,則自動賦值)
<jsp:setProperty name="javaBean實例名" property="javaBean屬性名" />(跟表單關聯,與*號的區別是這里對某個屬性進行匹配設值)
<jsp:setProperty name="javaBean實例名" property="javaBean屬性名" value="BeanValue" />(手工設置)
<jsp:setProperty name="javaBean實例名" property="propertyName" param="request對象中的參數名" />(跟request參數關聯)
-
<jsp:getProperty>
的作用:獲取指定javabean對象中的屬性值
<jsp:getProperty name="javaBean實例名" property="屬性名" />
-
param動作
,語法:<jsp:param name="參數名" value="參數值" />
,其常常與<jsp:forword>一起使用,作為其子標簽。 - 請求轉發到URL時增加新的參數1,2或者修改原表單中某字段的值
<jsp:forward page="URL">
<jsp:param name="參數名1" value="參數值1" />
<jsp:param name="參數名2" value="參數值2" />
</jsp:forward>
- 創建一個javaBean:User.java
// 公有類
public class User {
// 私有屬性
private String username;
private String password;
// 公有構造方法
public User() {
}
// getter、setter方法
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 新建并修改login.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登錄頁面</title>
</head>
<body>
<h1>系統登錄</h1>
<form action="userBean.jsp?mypass=77777" name="loginForm" method="post">
<table>
<tr>
<td>用戶名:</td>
<td><input type="text" name="username" value=""/></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="password" name="password" value=""/></td>
</tr>
<tr>
<%--colspan 屬性規定單元格可橫跨的列數--%>
<td colspan="2" ><input type="submit" value="登錄" /></td>
</tr>
</table>
</form>
</body>
</html>
- 創建并修改userBean.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
request.setCharacterEncoding("utf-8");
%>
<html>
<head>
<title>jsp動作元素useBean的使用</title>
</head>
<body>
<%--scope默認值是page,id就是一個javabean實例對象--%>
<jsp:useBean id="myUsers" class="com.zzw.po.User" scope="page"/>
<h1>使用userBean動作標簽來創建并賦值javaBean的實例</h1>
<%--name和上面的id要相同,'*'表示自動去匹配javaBean中所有屬性,若都匹配則調用set方法依次給屬性賦值--%>
<%--<jsp:setProperty name="myUsers" property="*" />--%>
<%--name和上面的id要相同,根據表單匹配某個屬性并予其賦值--%>
<%--<jsp:setProperty name="myUsers" property="username" />--%>
<%--name和上面的id要相同,與表單無關,通過手工給屬性賦值--%>
<%--<jsp:setProperty name="myUsers" property="username" value="lisi"/>
<jsp:setProperty name="myUsers" property="password" value="666"/>--%>
<%--通過URL中的參數給屬性賦值--%>
<jsp:setProperty name="myUsers" property="password" param="mypass"/>
<jsp:setProperty name="myUsers" property="username" />
<%--使用傳統表達式的方式來獲取用戶名和密碼的值--%>
<%--用戶名:<%=myUsers.getUsername() %><br/>
密碼:<%=myUsers.getPassword() %>--%>
用戶名:<jsp:getProperty name="myUsers" property="username"/><br/>
密碼:<jsp:getProperty name="myUsers" property="password" />
</body>
</html>
- javaBean的四個作用域范圍,使用useBean的scope屬性可以用來指定javaBean的作用范圍。
page
:僅在當前頁面有效,作用域范圍最小request
:可以通過HttpRequest.getAttribute()方法取得javaBean對象session
:可以通過HttpSession.getAttribute()方法取得javaBean對象application
:可以通過application.getAttribute()方法取得javaBean對象,作用域范圍最大
-
Model1
模型出現前,整個web應用的情況:幾乎全部由jsp頁面組成,jsp頁面接收處理客戶端請求,對請求處理后直接做出響應。弊端:在界面層充斥著大量的業務邏輯代碼和數據訪問層的代碼,web程序的可擴展性和可維護性非常差。JavaBean的出現可以使jsp頁面中使用JavaBean封裝的數據或者調用JavaBean的業務邏輯代碼,這樣大大提升了程序的可擴展性。
Model1的3層結構圖
- 使用jsp+javabean完成用戶登錄功能
- 新建用戶邏輯類:com.zzw.dao.UserDao.java
import com.zzw.po.User;
// 用戶邏輯類
public class UserDao {
// 用戶登錄方法
public boolean userLogin(User u) {
if("admin".equals(u.getUsername()) && "admin".equals(u.getPassword())) {
return true;
} else {
return false;
}
}
}
- 修改userBean.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="loginUser" class="com.zzw.po.User" scope="page"/>
<%--還要實例化一個用戶邏輯類UserDao--%>
<jsp:useBean id="userDao" class="com.zzw.dao.UserDao" scope="page"/>
<jsp:setProperty name="loginUser" property="*" />
<%
// 修改字符集
request.setCharacterEncoding("utf-8");
if(userDao.userLogin(loginUser)) {
session.setAttribute("loginUser", loginUser.getUsername());
request.getRequestDispatcher("login_success.jsp").forward(request, response);
} else {
response.sendRedirect("login_failure.jsp");
}
%>
- 新建并修改login_success.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登錄成功狀態</title>
</head>
<body>
登錄成功!
</body>
</html>
- 新建并修改login_failure.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登錄失敗狀態</title>
</head>
<body>
登錄失敗!
</body>
</html>
- 重啟tomcat服務器,訪問
http://localhost:8080/tomcatdemo/login.jsp
,用戶名和密碼都輸入"admin",結果顯示如下:
登錄成功
-
http協議的無狀態性
:(使用的協議是超文本傳輸協議)指的是當瀏覽器發送請求給服務器時,服務器響應客戶端請求。但是當同一個瀏覽器再次發送請求給服務器時,服務器并不知道它就是剛才那個瀏覽器。簡單地說,服務器不會記住你,所以就是無狀態協議
。 -
保存用戶狀態
的兩大機制:Session
和Cookie
。 -
Cookie
:中午名稱是"小甜品",是web服務器保存在客戶端的一系列文本信息。Cookie中對保存對象的大小是有限制的。典型應用一:判斷注冊用戶是否已經登錄網站
。典型應用二:"購物車"的處理
。 - Cookie的作用:
對特定對象的追蹤
;保存用戶網頁瀏覽記錄與習慣
;簡化登錄
。安全風險:容易泄露用戶信息
。 - jsp中創建和使用Cookie:
<%-- 創建Cookie對象 --%>
Cookie newCookie = new Cookie(String key, Object value);
<%-- 寫入Cookie對象 --%>
response.addCookie(newCookie);
<%-- 讀取Cookie對象 --%>
Cookie[] cookies = request.getCookies();
- 常用方法如下:
- void setMaxAge(int expiry):設置cookie的有效期,以秒為單位
- void setValue(String value):在cookie創建后,對cookie進行賦值
- String getName():獲取cookie的名稱
- String getValue():獲取cookie的值
- int getMaxAge():獲取cookie的有效時間,以秒為單位
Session和Cookie的區別
- 實現登錄時記住用戶名和密碼功能
- 修改login.jsp文件
<%@ page language="java" import="java.util.*,java.net.*"
contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
<h1>用戶登錄</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
// 字符編碼轉碼
username = URLDecoder.decode(c.getValue(), "utf-8");
}
if (c.getName().equals("password")) {
password = URLDecoder.decode(c.getValue(), "utf-8");
}
}
}
%>
<form name="loginForm" action="dologin.jsp" method="post">
<table>
<tr>
<td>用戶名:</td>
<td><input type="text" name="username" value="<%=username%>" /></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="password" name="password"
value="<%=password%>" /></td>
</tr>
<tr>
<td colspan="2"><input type="checkbox" name="isUseCookie"
checked="checked" />十天內記住我的登錄狀態</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登錄" /><input
type="reset" value="取消" /></td>
</tr>
</table>
</form>
</body>
</html>
- 修改dologin.jsp文件
<%@ page language="java" import="java.util.*,java.net.*"
contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting page</title>
</head>
<body>
<h1>登錄成功</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
//首先判斷用戶是否選擇了記住登錄狀態
String[] isUseCookies = request.getParameterValues("isUseCookie");
if (isUseCookies != null && isUseCookies.length > 0) {
//把用戶名和密碼保存在Cookie對象里面
String username = URLEncoder.encode(request.getParameter("username"), "utf-8");
//使用URLEncoder解決無法在Cookie當中保存中文字符串問題
String password = URLEncoder.encode(request.getParameter("password"), "utf-8");
Cookie usernameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
//設置最大生存期限為10天
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(864000);
// 添加cookie實例到response對象中
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
} else {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals("username") || c.getName().equals("password")) {
//設置Cookie失效
c.setMaxAge(0);
//重新保存。
response.addCookie(c);
}
}
}
}
%>
<a href="perInfo.jsp" target="_blank">查看用戶信息</a>
</body>
</html>
- 創建并修改perInfo.jsp文件
<%@ page language="java" import="java.util.*,java.net.*"
contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'perInfo.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>用戶信息</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
// url參數解碼
username = URLDecoder.decode(c.getValue(), "utf-8");
}
if (c.getName().equals("password")) {
password = URLDecoder.decode(c.getValue(), "utf-8");
}
}
}
%>
<BR> 用戶名:<%=username %><br> 密碼:<%=password %><br>
</body>
</html>
- 重啟tomcat服務器,訪問
http://localhost:8080/MyJavaWebApp/login.jsp
,結果顯示如下:
實現記住登錄賬號和密碼
記住用戶信息