上一篇文章JavaWeb-Servlet服務(wù)連接器(三)_Alphamilk的博客-CSDN博客
目錄
1.ServletContext通信
會(huì)話技術(shù)Cookie與Session
1.Cookie
2.Session
1.ServletContext通信
概念:代表了整個(gè)web應(yīng)用,用于與服務(wù)器實(shí)現(xiàn)通信
可以通過以下方法獲取該對(duì)象
方法 | 描述 |
---|---|
request.getServletContext() |
返回與給定請(qǐng)求關(guān)聯(lián)的Servlet上下文對(duì)象。 |
this.getServletContext() |
返回當(dāng)前Servlet的上下文對(duì)象。它是通過servlet類自動(dòng)繼承的方法,可以在當(dāng)前servlet中直接調(diào)用。 |
獲取的對(duì)象可以實(shí)現(xiàn)以下功能
獲取MIME類型(互聯(lián)網(wǎng)通信時(shí)候用到的文件類型)
方法 | 描述 |
---|---|
request.getServletContext().getMimeType(String file) |
返回給定文件的 MIME 類型。可以通過請(qǐng)求的 Servlet 上下文對(duì)象調(diào)用,傳入文件路徑或文件名作為參數(shù)。 |
this.getServletContext().getMimeType(String file) |
返回給定文件的 MIME 類型??梢栽诋?dāng)前 Servlet 中直接調(diào)用,傳入文件路徑或文件名作為參數(shù)。 |
常見的MIME類型
MIME類型 | 描述 |
---|---|
text/plain | 純文本 |
text/html | HTML文檔 |
text/css | CSS樣式表 |
application/json | JSON數(shù)據(jù) |
application/xml | XML數(shù)據(jù) |
application/pdf | Adobe PDF文件 |
application/msword | Microsoft Word文檔 |
image/jpeg | JPEG圖像 |
image/png | PNG圖像 |
案例代碼:
package com.company;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ContextDemo")
public class ServletContextdemo extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 定義文件名
String filename = "javaWeb.jpg";
// 通過request創(chuàng)建對(duì)象
ServletContext context = req.getServletContext();
// 通過HttpServlet本身的方法創(chuàng)建ServletContext
ServletContext context1 = this.getServletContext();
// 獲取文件名的mimeType類型
String mimeType = context.getMimeType(filename);
System.out.println("FileName:"+filename+" MIMEType:"+mimeType);
}
// 方法統(tǒng)一
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
2. 域?qū)ο螅▽?shí)現(xiàn)共享數(shù)據(jù))
通過以下方法實(shí)現(xiàn)
方法 | 描述 |
---|---|
setAttribute(String name, Object obj) |
將給定名稱和對(duì)象綁定在當(dāng)前范圍內(nèi)(如servlet上下文、會(huì)話或請(qǐng)求)。 |
getAttribute(String name) |
返回與給定名稱關(guān)聯(lián)的對(duì)象,如果沒有找到則返回null。 |
remove(String name) |
從當(dāng)前范圍中刪除具有給定名稱的屬性,并返回被刪除的屬性值,如果沒有找到則返回null。 |
?案例代碼:
設(shè)置共享變量類
package com.company;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/Contextdemo3")
public class Contextdemo3 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// 創(chuàng)建共享變量
context.setAttribute("msg","HelloWorld");
System.out.println("訪問ContextDemo3");
}
// 方法統(tǒng)一
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
獲取共享變量類
package com.company;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/Contextdemo4")
public class Contextdemo4 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// 獲取共享變量
Object msg =context.getAttribute("msg");
System.out.println("訪問ContextDemo4");
// 如果消息可以進(jìn)行轉(zhuǎn)型字符串則轉(zhuǎn)型為字符串
if (msg instanceof String){
System.out.println((String) msg);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
?3.獲取文件的真實(shí)路徑
方法名 | 描述 |
---|---|
getRealPath(String path) | 獲取指定路徑下資源在服務(wù)器文件系統(tǒng)中的真實(shí)路徑 |
案例代碼:
就以剛才javaWeb.jpg舉例,找到其在服務(wù)器中的位置
package com.company;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ContextDemo2")
public class ContextDemo2 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 使用HttpServlet創(chuàng)建對(duì)象
ServletContext context = this.getServletContext();
// 通過相對(duì)于部署的 Web 應(yīng)用程序的根目錄的路徑來獲取真實(shí)路徑
String realpath = context.getRealPath("/src/javaWeb.jpg");
System.out.println("在服務(wù)器中存放的路徑是:"+realpath);
}
// 方法統(tǒng)一
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
?對(duì)比可以發(fā)現(xiàn)確實(shí)是在該位置
會(huì)話技術(shù)Cookie與Session
1.Cookie
cookie是客戶端的會(huì)話數(shù)據(jù),并且將數(shù)據(jù)保存到客戶端瀏覽器,可以保存一些并不重要的信息,比如購物車網(wǎng)站,當(dāng)選好購物的商品的時(shí)候如果關(guān)閉了瀏覽器,如果沒有Cookie技術(shù)則會(huì)丟失購買記錄,需要重新進(jìn)行購物。
Cookie的創(chuàng)建、設(shè)置、獲取
方法名 | 描述 |
---|---|
Cookie(String name, String value) |
創(chuàng)建一個(gè)新的 Cookie 對(duì)象,使用給定的名稱和值 |
response.addCookie(Cookie cookie) |
將指定的 Cookie 添加到響應(yīng)中 |
response.getCookies() |
獲取響應(yīng)中包含的所有 Cookie,并將其以數(shù)組形式返回 |
Cookie生命周期
每一個(gè)Cookie都有一定的生命周期,當(dāng)超過有效時(shí)間時(shí)候就會(huì)失效,默認(rèn)情況下,Cookie的創(chuàng)建生命周期直到客戶端的瀏覽器關(guān)閉就失效,而如果不存在失效的情況下太多的Cookie被瀏覽器保存下來會(huì)造成大量的資源占用??梢酝ㄟ^以下方法控制生命周期
方法名 | 描述 |
---|---|
setMaxAge(int seconds) |
設(shè)置 Cookie 的最大存活時(shí)間(以秒為單位)。 |
- 當(dāng) seconds 為 0 時(shí),表示該 Cookie 將立即過期并從客戶端刪除。 |
|
- 當(dāng) seconds 為負(fù)數(shù)時(shí),表示該 Cookie 是一個(gè)會(huì)話 Cookie,只在用戶會(huì)話期間有效,關(guān)閉瀏覽器后將被刪除。 |
|
- 當(dāng) seconds 大于0時(shí),表示該 Cookie 將在指定的秒數(shù)后過期。 |
創(chuàng)建Cookie的案例代碼:
設(shè)置Cookie類(案例情景:在成功登陸一些網(wǎng)站時(shí)候,就授予Cookie用以可以記錄用戶的操作)
package com.company;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 創(chuàng)建一個(gè)Cookie表示購物袋中有一輛蘭博基尼,并且傳入多個(gè)cookie
Cookie cookie = new Cookie("shoppingMap","Lamborghini");
Cookie cookie1 = new Cookie("login-id","1234");
// 第一個(gè)保留七天數(shù)據(jù),第二個(gè)默認(rèn)處理
cookie.setMaxAge(60*60*7);
resp.addCookie(cookie);
resp.addCookie(cookie1);
}
// 方法統(tǒng)一處理
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
訪問Cookie類
package com.company;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookies[] = req.getCookies();
// 輸出所有的Cookie數(shù)據(jù)
for (Cookie c:cookies) {
String name = c.getName();
String value = c.getValue();
System.out.println("CookieName:"+name+" CookieValue:"+value);
}
}
// 統(tǒng)一方法處理
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
查看發(fā)送的數(shù)據(jù)包:
Cookie的特點(diǎn)與作用
特點(diǎn):
- cookie的內(nèi)容存儲(chǔ)在客戶端的瀏覽器上
- 瀏覽器對(duì)單個(gè)cookie的大小有限制,并且對(duì)同一個(gè)域名的cookie的數(shù)量也有限制
作用:
- cookie常用于存儲(chǔ)少量不太敏感的數(shù)據(jù)
- 在未登陸的情況下能夠?qū)崿F(xiàn)服務(wù)器對(duì)用戶的身份識(shí)別
注意:cookie不應(yīng)該用于記錄用戶的登陸的唯一標(biāo)識(shí),因?yàn)槿绻腥送ㄟ^偽造cookie的方式(比如sql注入,或者csrf外部繞過)從而登陸到相關(guān)的網(wǎng)站,并對(duì)用戶的信息進(jìn)行非法修改,造成損失
2.Session
Seesion也是一門服務(wù)器的會(huì)話技術(shù),但是相比與Cookie,其數(shù)據(jù)保存在服務(wù)器中。一般用來識(shí)別與跟蹤用戶的狀態(tài)信息。
Session的創(chuàng)建、使用
方法 | 描述 |
---|---|
HttpSession session = request.getSession() |
創(chuàng)建或獲取當(dāng)前請(qǐng)求的 HttpSession 對(duì)象,如果不存在則會(huì)創(chuàng)建一個(gè)新的。 |
session.getAttribute(String name) |
獲取指定名稱的屬性值,返回一個(gè) Object 類型的值。 |
session.setAttribute(String name, Object value) |
設(shè)置指定名稱的屬性值,將 Object 類型的值存儲(chǔ)到 Session 中。 |
session.removeAttribute(String name) |
移除指定名稱的屬性值。 |
案例代碼:創(chuàng)建session對(duì)象并賦值
創(chuàng)建類
package com.company;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/SessionDemo1")
public class SessionDemo1 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 創(chuàng)建Session
HttpSession session = req.getSession();
session.setAttribute("用戶name","AlphaMilk");
System.out.println("設(shè)置session成功");
}
// 方法統(tǒng)一
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
獲取session類:
package com.company;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/SessionDemo2")
public class SessionDemo2 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 告訴瀏覽器服務(wù)器的編碼方式是utf-8
resp.setHeader("content-type","text/html;charset=utf-8");
// 獲取請(qǐng)求頭的session對(duì)象
HttpSession session = req.getSession();
// 創(chuàng)建輸出流,將session內(nèi)容輸出到瀏覽器中
PrintWriter writer = resp.getWriter();
writer.write("<h1>歡迎用戶"+session.getAttribute("用戶id")+"</h1>");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
?問題引出:如果客戶端瀏覽器不小心關(guān)閉,再次開啟瀏覽器獲取到的session將是不同的對(duì)象。那么該如何解決這個(gè)問題呢?
Session 的實(shí)現(xiàn)通常依賴于 Cookie。每次創(chuàng)建 Session 時(shí),會(huì)生成一個(gè)對(duì)應(yīng)的 Cookie,其中包含了一個(gè)稱為 JSESSIONID 的標(biāo)識(shí)符,用于唯一標(biāo)識(shí)該 Session 對(duì)象。
在客戶端發(fā)起請(qǐng)求時(shí),瀏覽器會(huì)自動(dòng)將該 Cookie 攜帶到服務(wù)器端,服務(wù)器通過解析 Cookie 中的 JSESSIONID,就能夠找到對(duì)應(yīng)的 Session 對(duì)象,從而實(shí)現(xiàn)狀態(tài)的保持和用戶身份的識(shí)別。
?實(shí)現(xiàn)session持久化
解決方法本質(zhì)就是創(chuàng)建一個(gè)一模一樣的cookie中JSESSIONID和值
案例代碼:
package com.company;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/SessionDemo3")
public class SessionDemo3 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 創(chuàng)建session對(duì)象
HttpSession session = req.getSession();
// 創(chuàng)建對(duì)應(yīng)的cookie對(duì)象
Cookie cookie = new Cookie("JSESSIONID",session.getId());
// 設(shè)置生命周期
cookie.setMaxAge(60*60);
resp.addCookie(cookie);
// 獲取session對(duì)象的id
System.out.println(req.getSession().getId());
}
// 實(shí)現(xiàn)方法統(tǒng)一
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
第一次獲取然后關(guān)閉瀏覽器重新獲取id
Session的銷毀
- 服務(wù)器關(guān)閉
- session調(diào)用invalidate()
- session修改默認(rèn)失效時(shí)間
????????session的默認(rèn)失效時(shí)間是30分鐘如果想要修改需要在項(xiàng)目的總web.xml配置中設(shè)置?
<session-config>
<session-timeout>30</session-timeout>
</session-config>
下一篇文章:文章來源:http://www.zghlxwxcb.cn/news/detail-649280.html
JavaWeb-Filter過濾器_Alphamilk的博客-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-649280.html
到了這里,關(guān)于JavaWeb-Servlet服務(wù)連接器(終)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!