[toc]
一、背景
- 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://www.cnblogs.com/zhuhuix/p/"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}用戶登錄
<body>
