一、背景
- Java Servlet可以說是一項非常久遠的技術了,甚至可以說是Java Web應用的起源。也就是說真正瞭解了這項技術的原理與實現細節,我們就掌握了Java Web的基礎,也對以後能上手基於Java Servlet的框架起到事半功倍的作用。
- 本文旨在重溫與Java Servlet密切相關的一些技術細節。
二、請求與響應
- Servlet的核心任務是處理請求Request,並給出響應Response,這也是Servlet存在的真正意義。
2.1、Http請求
- 在Java Web應用開發中,99.999%用到的都是Http請求
/**
* Servlet處理HTTP GET/POST請求
*/
public class HttpServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp {
...
}
}
-
HTTP存在GET/POST請求,Servlet是如何分辨的呢?
- GET請求,請求的數據會附在URL之後(就是把數據放置在HTTP協議頭中),以?分割URL和傳輸數據,多個參數用&連接
- POST請求:把提交的數據放置在是HTTP包的Body中。
## GET和POST請求的區別
# GET請求
GET /books/?name=computer&num=1 HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
# 注意最後一行是空行
# POST請求
POST /books/add HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
# 以下是POST請求Body
name=computer&num=1
- HttpServlet類中的Service方法根據Http請求的類型GET/POST分別調用doGet或doPost
/**
* HttpServlet類Service方法
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
- 對於Http Request請求,我們還需要理解冪等的概念:對同一個系統,使用同樣的條件,一次請求和重複的多次請求對系統資源的影響是一致的。
- 根據以上定義,我們認爲GET請求一般情況下是冪等的(GET請求不會引起服務資源的變更),而POST請求是非冪等的(POST請求會提交數據並造成數據更改,造成不可逆,比如多次POST提交訂單數據)。
- Servlet可以通過API獲取到Http請求的相關數據
API | 備註 |
---|---|
request.getParameter("參數名") | 根據參數名獲取參數值(注意,只能獲取一個值的參數) |
request.getParameterValue("參數名“) | 根據參數名獲取參數值(可以獲取多個值的參數) |
request.getMethod | 獲取Http請求方式 |
request.getHeader("User-Agent") | 獲取用臺瀏覽器信息 |
request.getCookies | 獲取與請求相關的Cookies |
request.getSession | 獲取與用戶相關的會話 |
... | ... |
2.2、Http響應
- 響應是爲了向用戶發送數據,Servlet需要處理的是封裝成Http響應消息的HttpServletResponse對象。
- Http響應一般返回給瀏覽器HTML頁面,再由瀏覽器解析HTML呈現給用戶。
- 但Http響應發送HTML頁面並不是全部,比如用戶需要通過網站下載某個文件,那Http響應需要返回字節流。
protected void doGet(HttpServletRequest req, HttpServletResponse resp){
// 這是一個字節流
resp.setContentType("application/octet-stream");
resp.setHeader("Content-disposition", "attachment;filename=" + filename);
InputStream fis = this.getClass().getResourceAsStream("download.xlsx");
OutputStream os = resp.getOutputStream();
byte[] bis = new byte[1024];
while (-1 != fis.read(bis)) {
os.write(bis);
}
}
- Servlet設置Http響應頭控制瀏覽器的行爲
//設置refresh響應頭控制瀏覽器每隔1秒鐘刷新一次
response.setHeader("refresh", "1");
//可分別通過三種方式禁止緩存當前文檔內容
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache")
// 重定向:收到客戶端請求後,通知客戶端去訪問另外一個web資源
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// 通過sendRedirect方法實現請求重定向
resp.sendRedirect(req.getContextPath() + "/welcome.jsp");
}
// 請求分派
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
req.getRequestDispatcher("/result.jsp").forward(req,resp);
}
- Servlet與HTTP 狀態碼
代碼 | 消息 | 描述 |
---|---|---|
200 | OK | 請求成功。 |
401 | Unauthorized | 所請求的頁面需要授權 |
404 | Not Found | 服務器無法找到所請求的頁面。 |
500 | Internal Server Error | 未完成的請求。服務器遇到了一個意外的情況 |
... | ... | ... |
// 返回HTTP 500狀態碼
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
resp.sendError(500);
}
三、ServletConfig
- 在每個Servlet運行時,有可能需要一些初始化參數,比如,文件使用的編碼,共享的資源信息等。
- 這些初始化參數可以在 web.xml 文件中使用一個或多個 <init-param> 元素進行描述配置。當 容器 初始化一個 Servlet 時,會將該 Servlet 的配置信息封裝,並通過 init(ServletConfig)方法將 ServletConfig 對象的引用傳遞給 Servlet。
3.1 測試ServletConfig參數
- 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<!-- 設置該servlet的管理員郵箱地址 -->
<init-param>
<param-name>adminEmail</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
</web-app>
- 在servlet代碼中進行如下調用:
public class HttpServletDemo extends HttpServlet {
// 重寫Get請求方法,返回一個表單頁面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/html");
resp.setCharacterEncoding("GBK");
PrintWriter out =resp.getWriter();
out.println("<html><body>");
out.println("管理員郵箱:");
out.println(getServletConfig().getInitParameter("adminEmail"));
out.println("<br>");
out.println("</body></html>");
}
}
四、ServletContext
-web應用同樣也需要一些初始化的參數,但 相對於每一個Servlet有一個ServletConfig來說,一個Web應用(確切的說是每個JVM)僅有一個ServletContext來存放這些參數,這個ServletContext對Web應用中的每個Servlet都可用。
4.1 測試ServletContext參數
- 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 設置web應用的統一標題欄 -->
<context-param>
<param-name>title</param-name>
<param-value>My-App網站</param-value>
</context-param>
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>http-demo</servlet-name>
<url-pattern>/http-demo</url-pattern>
</servlet-mapping>
</web-app>
- 在servlet代碼中進行如下調用:
public class HttpServletDemo extends HttpServlet {
// 重寫Get請求方法,返回一個表單頁面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/html");
resp.setCharacterEncoding("GBK");
PrintWriter out =resp.getWriter();
out.println("<html><body>");
out.println("<title>"+getServletContext().getInitParameter("title")+"</title>");
out.println("管理員郵箱:");
out.println(getServletConfig().getInitParameter("adminEmail"));
out.println("<br>");
out.println("</body></html>");
}
}
- 注意點:
// 在web應用中,以下兩句代碼等價
getServletContext().getInitParameter("title");
getServletConfig().getServletContext().getInitParameter("title");
4.2、ServletContext屬性
- 通過編程的方式,可以給ServletContext綁定屬性,使得web應用中的Servlet對象可以使用該全局屬性。
// 重寫Post請求方法,提交表單上的數據,並返回結果頁面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer age = Integer.parseInt(req.getParameter("age"));
if (name != null && age != null) {
User user = new User(name, age);
req.setAttribute("name", name);
req.setAttribute("age", age);
// 設置提交成功次數屬性,並同步加鎖,防止多線程併發異常
synchronized (getServletContext()) {
if (user.checkName()) {
Long postCount = getServletContext().getAttribute("postCount") == null ? 1L
: Long.parseLong(getServletContext().getAttribute("postCount").toString()) + 1L;
getServletContext().setAttribute("postCount", postCount);
req.setAttribute("result", "登記成功" + "! 總共已有" + postCount + "人數登記!!");
} else {
req.setAttribute("result", "登記失敗:名稱中包含非法字符");
}
}
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
- 屬性與參數的區別
屬性 | 參數 | |
---|---|---|
設置方法 | setAttribute(String name,Object value) | 只能在web.xml中設置 |
返回類型 | Object | String |
獲取方法 | getAttribute(String name). | getInitParameter(String s) |
五、屬性的作用域
- 除了ServletContext可以設置屬性外,HttpSession會話、HttpServletRequest請求都可以設置和使用屬性。但這三者的作用域是不同的,可參見下表:
屬性作用域 | 備註 | |
---|---|---|
ServletContext | web應用存活期間都可以設置並使用屬性;應用關閉上下文撤消後相應屬性也會消失 | 各個Servlet都可以使用,但線程不安全,一般適在於常量屬性等,比如數據庫連接 |
HttpSession | HttpSession應用存活期間都可以設置並使用屬性;會話超時或被人爲撤消後相應屬性也會消失 | 與會話相關的都可以使用,比如電商網站的購物車屬性 |
HttpServletRequest | 每次請求生成時可設置或使用屬性,直到這個請求在service方法中消失 | 請求中屬性是線程安全的,類似於局部變量 |
六、HttpSession
- Session就是爲了讓服務器有能力分辨出不同的用戶。
- 客戶端在第一次請求時沒有攜帶任何sessionId,服務端Servlet容器就會給客戶端創建一個HttpSession對象 存儲在服務器端,然後給這個對象創建一個sessionID 作爲唯一標識。同時
這個sessionID還會放在一個cookie裏,通過response返回客戶端。- 客戶端第二次發出請求,cookie中會攜帶sessionId,servlet容器拿着這個sessionID在服務器端查找對應的HttpSession對象,找到後就直接拿出來使用。
- Servlet會爲不同的客戶端創建不同的sessionId及session對象,代表不同的狀態。
6.1 HttpSession的關鍵方法
- 關鍵方法
方法 | 描述 |
---|---|
getSession() | 獲取Session 對象 |
setAttribute() | 在Session 對象中設置屬性 |
getAttribute() | 在Session 對象中獲取屬性 |
removeAttribute() | 在Session 對象中刪除屬性 |
invalidate() | 使Session 對象失效 |
setMaxInactiveInterval() | 設置Session 對象最大間隔時間(在這段時間內,客戶端未對這個會話有新的請求操作,該會話就會撤消) |
6.2 簡易的購物車使用HttpSession
-
網站後臺通過會話保存用戶的購物車狀態,用戶在退出網站後在會話的有效時間段內重新進入網站,購物車狀態不消失。
-
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>title</param-name>
<param-value>購物網站</param-value>
</context-param>
<!-- 網站session失效時間爲30分鐘 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- 登錄servlet -->
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>http-demo</servlet-name>
<url-pattern>/http-demo</url-pattern>
</servlet-mapping>
<!-- 購物車servlet -->
<servlet>
<servlet-name>cart</servlet-name>
<servlet-class>demo.servlet.CartServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cart</servlet-name>
<url-pattern>/cart</url-pattern>
</servlet-mapping>
</web-app>
- 購物網站登錄頁面Servlet:
/**
* 購物網站登錄頁面
*
* @author zhuhuix
* @date 2020-08-28
*/
public class HttpServletDemo extends HttpServlet {
//static int i=0 ;
// 重寫Get請求方法,返回登錄表單頁面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setAttribute("title", getServletContext().getInitParameter("title"));
req.getRequestDispatcher("/form.jsp").forward(req, resp);
}
// 重寫Post請求方法,進行登錄,登錄成功後跳車購物車頁面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer password = Integer.parseInt(req.getParameter("password"));
if (name != null && password != null) {
req.getSession().setAttribute("name",name);
RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
view.forward(req, resp);
}
}
}
- 購物網站登錄頁面視圖:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}用戶登錄</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="http-demo" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-3">用戶登錄</h4>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">用戶名</label>
<div class="col-sm-3">
<input name="name" type="text" class="form-control" placeholder="請輸入用戶名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">密碼</label>
<div class="col-sm-3">
<input name="password" type="password" class="form-control" placeholder="請輸入密碼">
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-3">
<button class="btn btn-primary">點擊登錄</button>
</div>
</div>
</form>
</div>
</body>
</html>
- 購物車頁面視圖:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}購物車</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="cart" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-1">${name}的購物車</h4>
</div>
<table class="table table-bordered table-condensed" style="width: 30%">
<thead>
<tr>
<td>貨物</td>
<td>數量</td>
</tr>
</thead>
<tbody>
<tr>
<td>手機</td>
<td><input type="number" name="phoneNumber" value=${phoneNumber}> </td>
</tr>
<tr>
<td>電腦</td>
<td><input type="number" name="pcNumber" value=${pcNumber}> </td>
</tr>
<tr>
<td>書本</td>
<td><input type="number" name="bookNumber" value=${bookNumber}> </td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-sm-1 col-sm-offset-1">
<button class="btn btn-primary">點擊提交</button>
</div>
</div>
</form>
</div>
</body>
</html>
- 購物車的Servlet:
/**
* 購物車Servlet
*
* @author zhuhuix
* @date 2020-08-29
*/
public class CartServlet extends javax.servlet.http.HttpServlet {
// 重寫Post請求方法,提交購物車的數據,並返回結果頁面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查找頁面上的購物數量,並放入session中
req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
- 購物結果視圖頁面:
<!--結果頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}購物結果</title>
</head>
<body>
<div class="container">
<div class="row">
<h3 class="col-sm-3 col-sm-offset-1">${name}的購物結果</h3>
</div>
<table class="table table-bordered table-condensed" style="width: 30%">
<thead>
<tr>
<td>已購貨物</td>
<td>已購數量</td>
</tr>
</thead>
<tbody>
<tr>
<td>手機</td>
<td>${phoneNumber} </td>
</tr>
<tr>
<td>電腦</td>
<td>${pcNumber}</td>
</tr>
<tr>
<td>書本</td>
<td>${bookNumber} </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
- HttpSession狀態測試
- 用戶登錄網站後在購物車頁面提交購物結果:
- 用戶退出網站,重新登錄 後進入購物車頁面,網站後臺將HttpSession中的數據重新調取到頁面進行顯示:
- 在web.xml中將會話失效時間改爲一分鐘,並重啓網站,進行購物車提交
<!-- 網站session失效時間爲1分鐘 -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
- 退出網站,超過一分鐘後重新登錄,並查看購物車情況
- 購物車已空空如也
七、監聽器
- 監聽器Listener又稱爲監聽者,Listener的設計爲開發Servlet應用程序提供了一種快捷的手段,能夠方便地從另一個縱向維度控制程序和數據,正所謂旁觀者清。
- 監聽器採用了觀察者設計模式,監聽範圍包括ServletContext、HttpSession、HttpRequest。
7.1 監聽器測試--在線會話數統計
- 在web.xml中進行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>title</param-name>
<param-value>My-App網站</param-value>
</context-param>
<!-- 監聽者 負責監聽HttpSession創建與銷燬-->
<listener>
<listener-class>demo.servlet.HttpSessionListenerDemo</listener-class>
</listener>
<!-- 登錄servlet -->
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>http-demo</servlet-name>
<url-pattern>/http-demo</url-pattern>
</servlet-mapping>
</web-app>
- 創建監聽器類:
/**
* HttpSession監聽器測試:統計當前服務器在線人數
*/
public class HttpSessionListenerDemo implements javax.servlet.http.HttpSessionListener {
@Override
public void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
SessionStatics.increase();
}
@Override
public void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent) {
SessionStatics.decrease();
}
}
/**
* 計數類
*/
public class SessionStatics {
private static volatile Long count=0L;
public static void increase(){
synchronized (SessionStatics.class) {
count++;
}
}
public static void decrease(){
synchronized (SessionStatics.class) {
count--;
}
}
public static Long getCount(){
return count;
}
}
- 創建用戶登錄的servlet代碼:
/**
* HttpServlet模擬一個登錄頁面
*
* @author zhuhuix
* @date 2020-08-28
*/
public class HttpServletDemo extends HttpServlet {
// 重寫Get請求方法,返回一個表單頁面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setAttribute("title", getServletContext().getInitParameter("title"));
req.getRequestDispatcher("/form.jsp").forward(req, resp);
}
// 重寫Post請求方法,提交表單上的數據,並返回結果頁面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer password = Integer.parseInt(req.getParameter("password"));
if (name != null && password != null) {
// checkUserAndPassword
req.setAttribute("name", name);
req.setAttribute("result","登錄成功,當前在線人數:"+SessionStatics.getCount());
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
}
- 設計用戶登錄與登錄結果的視圖頁面:
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}用戶登錄</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="http-demo" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-3">用戶登錄</h4>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">用戶名</label>
<div class="col-sm-3">
<input name="name" type="text" class="form-control" placeholder="請輸入用戶名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">密碼</label>
<div class="col-sm-3">
<input name="password" type="password" class="form-control" placeholder="請輸入密碼">
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-3">
<button class="btn btn-primary">點擊登錄</button>
</div>
</div>
</form>
</div>
</body>
</html>
<!--結果頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}登錄結果</title>
</head>
<body>
<div class="container">
<div class="row">
<h3 class="col-sm-3 col-sm-offset-3">登錄結果</h3>
</div>
<div class="row">
<label class="col-sm-3 col-sm-offset-3">姓名:${name} </label>
</div>
<div class="row">
<label class="col-sm-3 col-sm-offset-3"> ${result}</label>
</div>
</div>
</body>
</html>
- 結果演示:
7.2 特殊的監聽器
- HttpSessionBindingListener監聽器可以JavaBean對象感知自己被綁定到Session中和從Session中刪除;且該監聽器不需要在web.xml聲明。
public class User implements javax.servlet.http.HttpSessionBindingListener {
private String name;
public User(String name){
this.name=name;
}
@Override
public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println(name+"加入session");
}
@Override
public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println(name+"移出session");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
...
// 測試HttpSessionBindingListener
req.getSession().setAttribute("user",new User(name));
}
八、過濾器
- 過濾器Filter允許你攔截請求和響應,通過編寫和配置一個過濾器,可以完成一些全局性的操作:比如安全驗證、統一編 碼處理、敏感字過濾等。
- Servlet API中提供了一個Filter接口,開發web應用時,如果編寫的Java類實現了這個接口,則把這個java類稱之爲過濾器Filter。
- 通過Filter技術,開發人員可以實現用戶在訪問某個目標資源之前,對訪問的請求和響應進行攔截。簡單說,就是可以實現web容器對某資源的訪問前截獲進行相關的處理,還可以在某資源向web容器返回響應前進行截獲進行處理。
8.1 過濾器的使用方法
- 定義一個類,實現接口Filter,並 重寫Filter接口類的方法;
/**
* 過濾器例子
*/
public class FilterDemo implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 過濾
System.out.println("攔截過濾...");
// 放行請求
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
- 配置過濾器攔截路徑。
<!-- web.xml -->
<!-- 過濾器配置 -->
<filter>
<filter-name>filterDemo</filter-name>
<filter-class>demo.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>filterDemo</filter-name>
<!-- 攔截路徑 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
8.2 過濾器的執行流程
- 當Web容器接受到一個對資源路徑的請求時,會判斷是否有過濾器與這個資源路徑相關聯。如果有,就把請求交給過濾器進行處理。
- 在過濾器程序中,可以改變請求的內容,或者重新設置請求的頭信息等操作,然後對請求放行發送給對應目標資源;當目標資源完成響應後,容器再次會將響應轉發給過濾器,這時候可以對響應的內容進行處理,然後再將響應發送到客戶端.。
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 前置過濾
System.out.println("攔截過濾{pre}");
// 放行請求
filterChain.doFilter(servletRequest,servletResponse);
// 後置過濾
System.out.println("攔截過濾{post}");
}
8.3 過濾器的生命週期
- 初始化init:服務器啓動時,進行創建Filter對象,然後調用init方法;該過程只執行一次,一般用於加載資源。
- 攔截過濾doFilter:每一次請求被都會被執行。
- 銷燬destroy:服務器正常關閉時,Filter對象會被銷燬。該過程只執行一次,一般用於釋放資源。
8.4 過濾器的攔截配置
- 攔截路徑配置:
- 攔截具體資源:比如/index.jsp,只有訪問index.jsp資源時,過濾器纔會執行。
- 攔截網站目錄:/demo ,訪問網站的demo目錄下的資源時,過濾器纔會執行。
- 後綴名攔截:比如 *.jsp,訪問所有後綴名爲jsp資源時,過濾器會執行。
- 攔截所有資源:比如/*,訪問網站下所有資源時,過濾器都會執行。
<!-- 攔截具體資源 -->
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/form.jsp</url-pattern>
</filter-mapping>
<!-- 攔截網站目錄 -->
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/demo</url-pattern>
</filter-mapping>
<!-- 後綴名攔截 -->
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!-- 攔截所有資源 -->
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 攔截方式配置:
- REQUEST : 瀏覽器直接請求時,過濾器纔會執行。
- FORWARD: 只有轉發訪問時,過濾器纔會執行。
- INCLUDE:包含訪問資源時,過濾器纔會執行。
- ERROR:錯誤跳轉資源時,過濾器纔會執行。
- ASYNC:異步訪問資源時,過濾器纔會執行。
<!-- 過濾器配置 -->
<filter>
<filter-name>filterDemo</filter-name>
<filter-class>demo.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/http-demo</url-pattern>
<!-- 瀏覽器直接請求時,過濾器會執行 -->
<dispatcher>REQUEST</dispatcher>
<!-- 轉發請求時,過濾器會執行 -->
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
8.5 過濾器鏈
- 過濾器可以鏈到一起,一個接一個地運行。
- 在web.xml中,哪個過濾器的filter-mapping先配置,則哪個過濾器先執行
<!-- 過濾器配置 -->
<filter>
<filter-name>filterDemo1</filter-name>
<filter-class>demo.filter.FilterDemo</filter-class>
</filter>
<!-- 哪個過濾器的filter-mapping先配置,則哪個過濾器先執行-->
<filter-mapping>
<filter-name>filterDemo1</filter-name>
<url-pattern>/http-demo</url-pattern>
</filter-mapping>
<filter>
<filter-name>filterDemo2</filter-name>
<filter-class>demo.filter.FilterDemo2</filter-class>
</filter>
<!-- 哪個過濾器的filter-mapping後配置,則哪個過濾器後執行-->
<filter-mapping>
<filter-name>filterDemo2</filter-name>
<url-pattern>/http-demo</url-pattern>
</filter-mapping>
8.5 過濾器的案例--登錄驗證
- 項目結構
- web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>title</param-name>
<param-value>購物網站</param-value>
</context-param>
<!-- 過濾器配置 -->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>demo.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 登錄驗證servlet -->
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>demo.servlet.LoginServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<!-- 購物車servlet -->
<servlet>
<servlet-name>cart</servlet-name>
<servlet-class>demo.servlet.CartServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cart</servlet-name>
<url-pattern>/cart</url-pattern>
</servlet-mapping>
</web-app>
- 登錄程序
/**
* 購物網站登錄頁面
*
* @author zhuhuix
* @date 2020-08-30
*/
public class LoginServlet extends HttpServlet {
// 重寫Get請求方法,返回一個登錄頁面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setAttribute("title", getServletContext().getInitParameter("title"));
req.getRequestDispatcher("/form.jsp").forward(req, resp);
}
// 重寫Post請求方法,提交用戶名與密碼
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer password = Integer.parseInt(req.getParameter("password"));
if (name != null && password != null) {
// 用戶登錄驗證通過後,設置用戶名稱屬性
req.getSession().setAttribute("name",name);
RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
view.forward(req, resp);
}
}
}
- 登錄頁面
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}用戶登錄</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="login" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-3">用戶登錄</h4>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">用戶名</label>
<div class="col-sm-3">
<input name="name" type="text" class="form-control" placeholder="請輸入用戶名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">密碼</label>
<div class="col-sm-3">
<input name="password" type="password" class="form-control" placeholder="請輸入密碼">
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-3">
<button class="btn btn-primary">點擊登錄</button>
</div>
</div>
</form>
</div>
</body>
</html>
- 購物車程序
/**
* 購物車Servlet
*
* @author zhuhuix
* @date 2020-08-29
*/
public class CartServlet extends javax.servlet.http.HttpServlet {
// 重寫Post請求方法,提交購物車的數據,並返回結果頁面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查找頁面上的購物數量,並放入session中
req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
- 購物車頁面
<!--表單頁面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}購物車</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="cart" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-1">${name}的購物車</h4>
</div>
<table class="table table-bordered table-condensed" style="width: 30%">
<thead>
<tr>
<td>貨物</td>
<td>數量</td>
</tr>
</thead>
<tbody>
<tr>
<td>手機</td>
<td><input type="number" name="phoneNumber" value=${phoneNumber}> </td>
</tr>
<tr>
<td>電腦</td>
<td><input type="number" name="pcNumber" value=${pcNumber}> </td>
</tr>
<tr>
<td>書本</td>
<td><input type="number" name="bookNumber" value=${bookNumber}> </td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-sm-1 col-sm-offset-1">
<button class="btn btn-primary">點擊提交</button>
</div>
</div>
</form>
</div>
</body>
</html>
- 程序測試
-
訪問購物車頁面:由於用戶未登錄,則會跳轉到登錄頁面
-
用戶輸入用戶名和密碼後進行登錄,登錄成功後會跳轉到購物車頁面。
-
用戶進行購物,並提交購物結果
-
退出頁面,在瀏覽器中再次訪問購物車頁面,可以看到過濾器判斷到用戶會話存在,已處於登錄狀態,直接跳轉到購物車頁面。