# Session
session在Web開發環境下的語義又有了新的擴展,它的含義是指一類用來在客戶端與服務器端之間保持狀態的解決方案。有時候Session也用來指這種解決方案的存儲結構。
### Session機制
session機制采用的是在服務器端保持 HTTP 狀態信息的方案 。
除了使用Cookie,Web應用程序中還經常使用Session來記錄客戶端狀態。Session是服務器端使用的一種記錄客戶端狀態的機制,使用上比Cookie簡單一些,相應的也增加了服務器的存儲壓力。
Session是另一種記錄客戶狀態的機制,不同的是Cookie保存在客戶端瀏覽器中,而Session保存在服務器上。客戶端瀏覽器訪問服務器的時候,服務器把客戶端信息以某種形式記錄在服務器上。這就是Session。客戶端瀏覽器再次訪問時只需要從該Session中查找該客戶的狀態就可以了。
如果說Cookie機制是通過檢查客戶身上的“通行證”來確定客戶身份的話,那么Session機制就是通過檢查服務器上的“客戶明細表”來確認客戶身份。Session相當于程序在服務器上建立的一份客戶檔案,客戶來訪的時候只需要查詢客戶檔案表就可以了。
當程序需要為某個客戶端的請求創建一個session時,服務器首先檢查這個客戶端的請求里是否包含了一個session標識(即sessionId),如果已經包含一個sessionId則說明以前已經為此客戶創建過session,服務器就按照session id把這個session檢索出來使用(如果檢索不到,可能會新建一個,這種情況可能出現在服務端已經刪除了該用戶對應的session對象,但用戶人為地在請求的URL后面附加上一個JSESSION的參數)。如果客戶請求不包含sessionId,則為此客戶創建一個session并且生成一個與此session相關聯的sessionId,這個session id將在本次響應中返回給客戶端保存。
***
session機制演示圖

***
代碼演示
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= session.getId() %>
</body>
</html>
~~~
在開發者工具中查看,第一發出時請求響應頭當中有Set-Cooie

再次請求時(刷新),響應頭當中將沒有Set-Cookie,而請求頭當中將有Cookie發回給服務器,

兩個Cookie完全一樣,以后的每次請求都會找到那個session對象,完成跟蹤
### 瀏覽器禁用Cookie
瀏覽器禁用Cookie后,每次請求客戶端都會得到一個新的Cookie,因為請求中將不再包含Cookie,服務器的session對象會再為這個請求新創建一個JESSIONID通過Cookie返回給了客戶端瀏覽器
***
### 保存session id的幾種方式
保存session id的方式可以采用cookie,這樣在交互過程中瀏覽器可以自動的按照規則把這個標識發送給服務器。
由于cookie可以被人為的禁用,必須有其它的機制以便在cookie被禁用時仍然能夠把session id傳遞回服務器,經常采用的一種技術叫做URL重寫,就是把session id附加在URL路徑的后面,附加的方式也有兩種,一種是作為URL路徑的附加信息,另一種是作為查詢字符串附加在URL后面。網絡在整個交互過程中始終保持狀態,就必須在每個客戶端可能請求的路徑后面都包含這個session id。
***
### Session cookie
session通過SessionID來區分不同的客戶, session是以cookie或URL重寫為基礎的,默認使用cookie來實現,系統會創造一個名為JSESSIONID的輸出cookie,這稱之為session cookie,以區別persistent cookies(也就是我們通常所說的cookie),session cookie是存儲于瀏覽器內存中的,并不是寫到硬盤上的,通常看不到JSESSIONID,但是當把瀏覽器的cookie禁止后,web服務器會采用URL重寫的方式傳遞Sessionid,這時地址欄看到
session cookie針對某一次會話而言,會話結束session cookie也就隨著消失了,而persistent cookie只是存在于客戶端硬盤上的一段文本。
關閉瀏覽器,只會是瀏覽器端內存里的session cookie消失,但不會使保存在服務器端的session對象消失,同樣也不會使已經保存到硬盤上的持久化cookie消失。
#### 持久化session cookie
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= session.getId() %>
<%
Cookie cookie = new Cookie("JESSIONID",session.getId());
cookie.setMaxAge(20);
%>
</body>
</html>
~~~
***
### HttpSession的生命周期
①什么時候創建HttpSession對象
**誤區:瀏覽器訪問服務端的任意一個JSP或Servlet,服務器就立即創建一個HttpSession對象**
1.page指令中session屬性設為false,無法使用session對象
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
~~~
2.直接訪問session.jsp無法獲取到session對象。先訪問另一個a.jsp,然后在訪問session.jsp,session對象會獲取到,但并不是session.jsp創建的session對象
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 如果有一個與當前頁面有關的session就返回,否則返回null -->
<%= request.getSession(false) %>
</body>
</html>
~~~
看上面兩段代碼得出結論:
A.若當前的JSP(或Servlet)是客戶端訪問的第一個資源,且JSP的page指令的session屬性為false,則服務器就不會為JSP創建一個HttpSession對象;
若當前JSP不是客戶端訪問的第一個資源。且其他頁面已經創建了一個HttpSession對象,則當前JSP頁面會返回上一個會話的HttpSession對象,而不會創建一個新的HttpSession對象
B.session="false"表示當前JSP頁面禁用session隱含變量,但可以使用其他顯式的HttpSession對象
C.對于Servlet而言,若Servlet是客戶端訪問的第一個WEB應用資源,則只有調用了request.getSession()或request.getSession(true)才會創建HttpSession對象
②什么時候銷毀HttpSession對象
**誤區:關閉瀏覽器就銷毀了session對象**
A.調用invalidate()方法,該方法使HttpSession時效
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
session.invalidate();
%>
<%= session.getId() %>
</body>
</html>
~~~
B.服務器卸載了當前WEB應用
C.超出session過期時間
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
session.invalidate();
// 設置session的過期時間,以秒為單位
session.setMaxInactiveInterval(5);
%>
<!-- 獲取session的過期時間,默認1800秒,即30分鐘 -->
<%= session.getMaxInactiveInterval() %>
<%= session.getId() %>
</body>
</html>
~~~
在conf目錄下的web.xml文件中也可以修改session的過期時間(全局的,所有的session的過期時間,若想單獨設置還是像上面那樣單獨設置)
~~~
<session-config>
<session-timeout>30</session-timeout>
</session-config>
~~~
***
課堂實例--1
session完成重新登錄
login.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
SessionId:<%= session.getId() %>
<br><br>
isNew:<%= session.isNew() %>
<br><br>
maxInactiveInternal:<%= session.getMaxInactiveInterval() %>
<br><br>
createTime:<%= session.getCreationTime() %>
<br><br>
lastAccessTime:<%= session.getLastAccessedTime() %>
<br><br>
<%
Object username = session.getAttribute("username");
if(username == null){
username = "";
}
%>
<form action="hello.jsp" method="post">
username:<input type="text" name="username" value="<%= username %>">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
hello.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
SessionId:<%= session.getId() %>
<br><br>
isNew:<%= session.isNew() %>
<br><br>
maxInactiveInternal:<%= session.getMaxInactiveInterval() %>
<br><br>
createTime:<%= session.getCreationTime() %>
<br><br>
lastAccessTime:<%= session.getLastAccessedTime() %>
<br><br>
Hello:<%= request.getParameter("username") %>
<br><br>
<%
session.setAttribute("username", request.getParameter("username"));
%>
<a href="login.jsp">重新登錄</a>
<a href="logout.jsp">注銷</a>
</body>
</html>
~~~
logout.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
SessionId:<%= session.getId() %>
<br><br>
isNew:<%= session.isNew() %>
<br><br>
maxInactiveInternal:<%= session.getMaxInactiveInterval() %>
<br><br>
createTime:<%= session.getCreationTime() %>
<br><br>
lastAccessTime:<%= session.getLastAccessedTime() %>
<br><br>
Bye:<%= session.getAttribute("username") %>
<br><br>
<%
session.invalidate();
%>
<a href="login.jsp">重新登錄</a>
</body>
</html>
~~~
***
課堂實例--2
完成用戶登錄
index.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="session.jsp" method="post">
username:<input type="text" name="username"> <br> <br>
password:<input type="password" name="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
session.jsp
~~~
<%@page import="com.neusoft.mvcapp.dao.Person"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% // 日期格式化器
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Person[] persons = {
// 基礎數據,保存三個人的信息
new Person("Tomcat", "password1", 34, dateFormat.parse("1982-01-01")),
new Person("HelloKitty", "hellokitty", 23, dateFormat.parse("1984-02-21")),
new Person("Garfield", "garfield_pass", 23, dateFormat.parse("1994-09-12")),
};
// 要顯示的消息
String message = "";
for (Person person : persons) {
// 遍歷基礎數據,驗證賬號、密碼
// 如果用戶名正確且密碼正確
if (person.getName().equalsIgnoreCase(request.getParameter("username"))
&& person.getPassword().equals(request.getParameter("password")))
{
// 登錄成功,設置將用戶的信息以及登錄時間保存到Session
session.setAttribute("person", person); // 保存登錄的Person
session.setAttribute("loginTime", new Date()); // 保存登錄的時間
response.sendRedirect(request.getContextPath() + "/20160123/welcome.jsp");
return;
}
}
// 登錄失敗
message = "用戶名密碼不匹配,登錄失敗。";
%>
<%= message %>
</body>
</html>
~~~
welcome.jsp
~~~
<%@page import="java.util.Date"%>
<%@page import="com.neusoft.mvcapp.dao.Person"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式化器
Person person = (Person) session.getAttribute("person"); // 獲取登錄的person
Date loginTime = (Date) session.getAttribute("loginTime"); // 獲取登錄時間
if (person != null) {
%>
<table border="2" cellpadding="10" cellspacing="0">
<tr>
<td>您的姓名:</td>
<td><%=person.getName()%></td>
</tr>
<tr>
<td>登錄時間:</td>
<td><%=loginTime%></td>
</tr>
<tr>
<td>您的年齡:</td>
<td><%=person.getAge()%></td>
</tr>
<tr>
<td>您的生日:</td>
<td><%=dateFormat.format(person.getBirthday())%></td>
</tr>
</table>
<%
}
%>
</body>
</html>
~~~
***
### 利用URL重寫實現Session跟蹤
如果瀏覽器禁用了Cookie,如何跟蹤session
login.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
SessionId:<%= session.getId() %>
<br><br>
isNew:<%= session.isNew() %>
<br><br>
maxInactiveInternal:<%= session.getMaxInactiveInterval() %>
<br><br>
createTime:<%= session.getCreationTime() %>
<br><br>
lastAccessTime:<%= session.getLastAccessedTime() %>
<br><br>
<%
Object username = session.getAttribute("username");
if(username == null){
username = "";
}
%>
<form action="<%=response.encodeURL("hello.jsp") %>" method="post">
username:<input type="text" name="username" value="<%= username %>">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
hello.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
SessionId:<%= session.getId() %>
<br><br>
isNew:<%= session.isNew() %>
<br><br>
maxInactiveInternal:<%= session.getMaxInactiveInterval() %>
<br><br>
createTime:<%= session.getCreationTime() %>
<br><br>
lastAccessTime:<%= session.getLastAccessedTime() %>
<br><br>
Hello:<%= request.getParameter("username") %>
<br><br>
<%
session.setAttribute("username", request.getParameter("username"));
%>
<a href="<%=response.encodeURL("login.jsp") %>">重新登錄</a>
<a href="<%=response.encodeURL("logout.jsp") %>">注銷</a>
</body>
</html>
~~~
此時查看網頁源代碼可以發現

HttpServletResponse接口中定義了兩個用于完成URL重寫方法:
encodeURL方法
encodeRedirectURL方法
***
課堂實例--2
Session的典型案例:簡易版購物車
***
課堂實例--3
Session的典型案例:一次性驗證碼
使用如下現成的一個類,直接復制即可
ValidateColorServlet
~~~
package com.neusoft.javaweb.checkcode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/validateColorServlet")
public class ValidateColorServlet extends HttpServlet {
//設置驗證圖片的寬度, 高度, 驗證碼的個數
private int width = 152;
private int height = 40;
private int codeCount = 4;
//驗證碼字體的高度
private int fontHeight = 4;
//驗證碼中的單個字符基線. 即:驗證碼中的單個字符位于驗證碼圖形左上角的 (codeX, codeY) 位置處
private int codeX = 0;
private int codeY = 0;
//驗證碼由哪些字符組成
char [] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789".toCharArray();
//初始化驗證碼圖形屬性
public void init(){
fontHeight = height - 2;
codeX = width / (codeCount + 2);
codeY = height - 4;
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定義一個類型為 BufferedImage.TYPE_INT_BGR 類型的圖像緩存
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//在 buffImg 中創建一個 Graphics2D 圖像
Graphics2D graphics = null;
graphics = buffImg.createGraphics();
//設置一個顏色, 使 Graphics2D 對象的后續圖形使用這個顏色
graphics.setColor(Color.WHITE);
//填充一個指定的矩形: x - 要填充矩形的 x 坐標; y - 要填充矩形的 y 坐標; width - 要填充矩形的寬度; height - 要填充矩形的高度
graphics.fillRect(0, 0, width, height);
//創建一個 Font 對象: name - 字體名稱; style - Font 的樣式常量; size - Font 的點大小
Font font = null;
font = new Font("", Font.BOLD, fontHeight);
//使 Graphics2D 對象的后續圖形使用此字體
graphics.setFont(font);
graphics.setColor(Color.BLACK);
//繪制指定矩形的邊框, 繪制出的矩形將比構件寬一個也高一個像素
graphics.drawRect(0, 0, width - 1, height - 1);
//隨機產生 15 條干擾線, 使圖像中的認證碼不易被其它程序探測到
Random random = null;
random = new Random();
graphics.setColor(Color.GREEN);
for(int i = 0; i < 30; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(20);
int y1 = random.nextInt(20);
graphics.drawLine(x, y, x + x1, y + y1);
}
//創建 randomCode 對象, 用于保存隨機產生的驗證碼, 以便用戶登錄后進行驗證
StringBuffer randomCode;
randomCode = new StringBuffer();
for(int i = 0; i < codeCount; i++){
//得到隨機產生的驗證碼數字
String strRand = null;
strRand = String.valueOf(codeSequence[random.nextInt(36)]);
randomCode.append(strRand);
//用隨機產生的顏色將驗證碼繪制到圖像中
graphics.setColor(Color.BLUE);
graphics.drawString(strRand, (i + 1)* codeX, codeY);
}
request.getSession().setAttribute("CHECK_CODE", randomCode.toString());
//禁止圖像緩存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//將圖像輸出到輸出流中
ServletOutputStream sos = null;
sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
~~~
check.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="checkCodeServlet" method="post">
username:<input type="text" name="username">
checkCode:<input type="text" name="check">
<img src="${pageContext.request.contextPath }/validateColorServlet">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
CheckCodeServlet
~~~
package com.neusoft.javaweb.checkcode;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CheckCodeServlet
*/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strCheckCode = request.getParameter("check");
String checkCode = (String)request.getSession().getAttribute("CHECK_CODE");
if(strCheckCode.equalsIgnoreCase(checkCode)) {
response.sendRedirect("hello.jsp");
}else {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter pr = response.getWriter();
pr.println("驗證碼錯誤");
}
}
}
~~~
***
### 相對路徑和絕對路徑
開發時建議編寫絕對路徑,相對路徑可能會出現問題
a.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>A Page</h1>
<a href="path/b.jsp">To B Page</a>
</body>
</html>
~~~
b.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>B Page</h1>
<a href="c.jsp">To C Page</a>
</body>
</html>
~~~
c.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>C Page</h1>
<a href="../a.jsp">To A Page</a>
</body>
</html>
~~~
運行a.jsp,能夠正確完成跳轉
但有些時候我們不是直接申請一個JSP資源,而是通過Servlet然后進行請求轉發
a.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>A Page</h1>
<a href="testsServlet">To B Page</a>
</body>
</html>
~~~
TestsServlet
~~~
package com.neusoft.shopping;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestsServlet
*/
@WebServlet("/testsServlet")
public class TestsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> cities = Arrays.asList("北京","阜新","阜新");
request.setAttribute("cities", cities);
request.getRequestDispatcher("/path/b.jsp").forward(request, response);
}
}
~~~
b.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>B Page</h1>
cities:<%= request.getAttribute("cities") %>
<br>
<a href="c.jsp">To C Page</a>
</body>
</html>
~~~
再運行a.jsp,b.jsp無法正確完成跳轉,因為a.jsp發送請求到Servlet,Servlet的路徑是WEB應用的根目錄,而b.jsp中的超鏈接相對路徑就是相對Servlet的相對路徑,自然找不到c.jsp,所以開發時一定要使用絕對路徑
JavaWEB開發中的“/”
①當前WEB應用的根路徑:http://localhost:8080/ykbbs/
--請求轉發時
--web.xml文件中映射Servlet訪問路徑
②WBN站點的根目錄:http://localhost:8080/
--超鏈接
--表單中的action
如何記憶:
若/需要交給Servlet容器來處理,則/就代表WEB應用根目錄(在其前面加上getContextPath即可-->request,applicaion都可以)
若/需要交給瀏覽器處理,則/就代表WEB站點目錄
***
### 避免表單的重復提交
①表單重復提交的情況
(1)在表單提交到一個Servlet,而Servlet又通過請求轉發的方式響應一個JSP或HTML頁面,此時地址欄還保留著Servlet的哪個路徑,在響應頁面點擊“刷新”;
(2)在響應頁面沒有到達時重復點擊“提交按鈕”
(3)點擊“返回”,在點擊“提交”
②不算表單重復提交的情況
點擊“返回”,“刷新”原表單頁面,再“提交”
token.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%= request.getContextPath() %>/tokenServlet" method="post">
Name:<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
TokenServlet
~~~
package com.neusoft.mvcapp.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TokenServlet
*/
@WebServlet("/tokenServlet")
public class TokenServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String name = request.getParameter("name");
System.out.println("name:"+name);
request.getRequestDispatcher("/token/success.jsp").forward(request, response);
}
}
~~~
success.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Success Page</h1>
</body>
</html>
~~~
有延遲的情況下,表單重復提交會比較的嚴重,會加重服務器的負擔
③如何避免表單重復提交
在表單中做一個標記,提交到Servlet時,檢查標記是否存在且是否和預定義的標記一直,若一致,則受理請求,并銷毀標記,若不一致或沒有標記,則響應“重復提交”。
token.jsp
~~~
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String tokenValue = new Date().getTime()+"";
session.setAttribute("token",tokenValue);
%>
<form action="<%= request.getContextPath() %>/tokenServlet" method="post">
<!-- 僅用一個隱藏域,不能實現標記功能 -->
<input type="hidden" value="<%= tokenValue %>" name="token">
Name:<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
~~~
tokenServlet
~~~
package com.neusoft.mvcapp.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TokenServlet
*/
@WebServlet("/tokenServlet")
public class TokenServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
Object token = session.getAttribute("token");
String tokenValue = request.getParameter("token");
if(token != null && token.equals(tokenValue)) {
session.removeAttribute("token");
}else {
response.sendRedirect(request.getContextPath()+"/token/tokened.jsp");
return;
}
String name = request.getParameter("name");
System.out.println("name:"+name);
// request.getRequestDispatcher("/token/success.jsp").forward(request, response);
response.sendRedirect(request.getContextPath()+"/token/success.jsp");
}
}
~~~
success.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Success Page</h1>
</body>
</html>
~~~
tokened.jsp
~~~
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Sorry,已經提交過了</h1>
</body>
</html>
~~~
***
### Session小結:
(1)簡介
Session是另一種記錄客戶狀態的機制,不同的是Cookie保存在客戶端瀏覽器中,而Session保存在服務器上。客戶端瀏覽器訪問服務器的時候,服務器把客戶端信息以某種形式記錄在服務器上。這就是Session。
Session由服務端生成,保存在服務器的內存、緩存、硬盤或數據庫中。
(2)工作原理
① 創建Session
當用戶訪問到一個服務器,如果服務器啟用Session,服務器就要為該用戶創建一個SESSION,在創建這個SESSION的時候,服務器首先檢查這個用戶發來的請求里是否包含了一個SESSION ID,如果包含了一個SESSION ID則說明之前該用戶已經登陸過并為此用戶創建過SESSION,那服務器就按照這個SESSION ID把這個SESSION在服務器的內存中查找出來(如果查找不到,就有可能為他新創建一個),如果客戶端請求里不包含有SESSION ID,則為該客戶端創建一個SESSION并生成一個與此SESSION相關的SESSION ID。這個SESSION ID是唯一的、不重復的、不容易找到規律的字符串,這個SESSION ID將被在本次響應中返回到客戶端保存,而保存這個SESSION ID的正是COOKIE,這樣在交互過程中瀏覽器可以自動的按照規則把這個標識發送給服務器。
② 使用Session
我們知道在IE中,我們可以在工具的Internet選項中把Cookie禁止,那么會不會出現把客戶端的Cookie禁止了,那么可以使用一種技術叫做URL重寫,**就是把Session id直接附加在URL路徑的后面**
(3)作用
Session的根本作用就是在服務端存儲用戶和服務器會話的一些信息。典型的應用有:
1、判斷用戶是否登錄。
2、購物車功能。
(4)生命周期
Session在用戶第一次訪問服務器的時候自動創建(特殊情況,session屬性為false,以及是否是第一個訪問資源)。需要注意只有訪問JSP、Servlet等程序時才會創建Session,只訪問HTML等靜態資源并不會創建Session。如果尚未生成Session,也可以使用request.getSession(true)強制生成Session。
Session生成后,只要用戶繼續訪問,服務器就會更新Session的最后訪問時間,并維護該Session。用戶每訪問服務器一次,無論是否讀寫Session,服務器都認為該用戶的Session“活躍(active)”了一次。
(5)Session有效期
由于會有越來越多的用戶訪問服務器,因此Session也會越來越多。為防止內存溢出,服務器會把長時間內沒有活躍的Session從內存刪除。這個時間就是Session的超時時間。如果超過了超時時間沒訪問過服務器,Session就自動失效了。
Session的超時時間為maxInactiveInterval屬性,可以通過對應的getMaxInactiveInterval()獲取,通過setMaxInactiveInterval(longinterval)修改。
Session的超時時間也可以在web.xml中修改。另外,通過調用Session的invalidate()方法可以使Session失效。
(6)常用方法
設置屬性:session.setAttribute(String name,Object obj)
獲取屬性:session.getAttribute(String name)
獲取SessionID:session.getId()
設置最大時效: setMaxInactiveInterval(int second)
使Session時效:invalidate()
***
### Cookie和Session的區別
#### 1、存放位置不同
Cookie保存在客戶端,Session保存在服務端。
#### 2 、存取方式的不同
Cookie中只能保管ASCII字符串,假如需求存取Unicode字符或者二進制數據,需要先進行編碼。Cookie中也不能直接存取Java對象。若要存儲略微復雜的信息,運用Cookie是比較艱難的。
而Session中能夠存取任何類型的數據,包括而不限于String、Integer、List、Map等。Session中也能夠直接保管Java Bean乃至任何Java類,對象等,運用起來十分便當。能夠把Session看做是一個Java容器類。
#### 3、安全性(隱私策略)的不同
Cookie存儲在瀏覽器中,對客戶端是可見的,客戶端的一些程序可能會窺探、復制以至修正Cookie中的內容。而Session存儲在服務器上,對客戶端是透明的,不存在敏感信息泄露的風險。 假如選用Cookie,比較好的方法是,敏感的信息如賬號密碼等盡量不要寫到Cookie中。最好是像Google、Baidu那樣將Cookie信息加密,提交到服務器后再進行解密,保證Cookie中的信息只要本人能讀得懂。而假如選擇Session就省事多了,反正是放在服務器上,Session里任何隱私都能夠有效的保護。
#### 4、有效期上的不同
只需要設置Cookie的過期時間屬性為一個很大很大的數字,Cookie就可以在瀏覽器保存很長時間。 由于Session依賴于名為JSESSIONID的Cookie,而Cookie JSESSIONID的過期時間默許為30分鐘,但是一旦關閉了瀏覽器(一次會話結束),該Session就會失效。
#### 5、對服務器造成的壓力不同
Session是保管在服務器端的,每個用戶都會產生一個Session。假如并發訪問的用戶十分多,會產生十分多的Session,耗費大量的內存。而Cookie保管在客戶端,不占用服務器資源。假如并發閱讀的用戶十分多,Cookie是很好的選擇。
- 第一章 配置和安裝Tomcat
- 第二章 Servlet(一)
- 第三章 Servlet(二)
- 練習 一 . Servlet配置級獲取初始化參數
- 第四章 JSP(一)
- 第五章 JSP(二)
- 第六章 MVC設計模式
- 第七章 Cookie
- 第八章 Session
- 練習 二 . 簡易版購物車
- 第九章 EL表達式
- 第十章 JSTL
- 第十一章 過濾器
- 第十二章 監聽器
- 第十三章 文件的上傳與下載
- 復習總結
- 如何手動啟動Tomcat
- 如何修改Tomcat端口號
- 如何在web.xml中配置Servlet
- Servlet生命周期
- load-on-startup參數
- Servlet映射路徑
- POST和GET的區別
- JSP中9個隱式對象及功能
- 請求轉發及請求重定向的區別
- JSP指令有哪些
- 簡述對MVC設計模式的理解
- 簡述Cookie機制
- 簡述Session機制
- HttpSession的生命周期
- Cookie和Session有什么區別
- 簡述創建過濾器步驟
- 過濾器經典案例--統一編碼字符集
- getParameter與getAttribute的區別
- JSP頁面中可以包含哪些元素
- web應用中,是如何跟蹤用戶的
- InteliJ創建web項目