Servlet
一税迷、Servlet簡(jiǎn)介
- Servlet是Sun公司提供的也可用于開發(fā)動(dòng)態(tài)web資源的技術(shù)
- Sun公司在其API中提供了一個(gè)Servlet接口永丝,用戶若想發(fā)一個(gè)動(dòng)態(tài)web資源,需兩個(gè)步驟:
- 編寫一個(gè)Java類箭养,實(shí)現(xiàn)Servlet接口
- 八開發(fā)好的Java類部署到web服務(wù)器中
- 按照一種約定俗稱的稱呼習(xí)慣慕嚷,通常我們也把實(shí)現(xiàn)了Servlet接口的Java程序稱之為Servlet
二、Servlet運(yùn)行過程
- Web瀏覽器發(fā)出HTTP請(qǐng)求給Web容器
- Web容器首次訪問創(chuàng)建目標(biāo)Servlet
- Web容器創(chuàng)建請(qǐng)求(request)和創(chuàng)建響應(yīng)(response)
- Web容器調(diào)用Servlet.service(request,response)
- service(request毕泌,response)獲取請(qǐng)求信息喝检。并把響應(yīng)寫入響應(yīng)信息返回給Web容器
- Web容器發(fā)出HTTP響應(yīng)給Web瀏覽器
- 注意:service() 方法由容器調(diào)用,開發(fā)人員不用對(duì) service() 方法做任何動(dòng)作撼泛,只需要根據(jù)來自客戶端的請(qǐng)求類型來重寫 doGet() 或 doPost() 即可
三挠说、Servlet實(shí)現(xiàn)類
- Servlet接口Sun公司定義了兩個(gè)默認(rèn)實(shí)現(xiàn)類。分別為GenericServlet愿题、HttpServlet
- HttpServlet是指能夠處理Http請(qǐng)求的Servlet纺涤,它在原有的Servlet接口上添加了一些與HTTP協(xié)議處理方法,它比原有接口功能更強(qiáng)大抠忘,因此通常使用該類,由于在實(shí)現(xiàn)Servlet接口時(shí)覆寫了service方法外永,該方法體內(nèi)的代碼會(huì)自動(dòng)判斷用戶的請(qǐng)求方法崎脉,因此在編寫Servlet時(shí),通常只需要覆寫doGet和doPost方法伯顶,而不需要去覆寫service方法
四囚灼、doGet和doPost的區(qū)別
-
form運(yùn)行方式
- 當(dāng)form框里面的method為get時(shí),執(zhí)行doGet方法
- 當(dāng)form框里面的method為post時(shí)祭衩,執(zhí)行doPost方法
-
生成方式
- doGet有四種:
- 直接在URL地址欄中輸入U(xiǎn)RL
- 網(wǎng)頁(yè)中的超鏈接
- form中method為get
- form中method為空時(shí)灶体,默認(rèn)是get提交
- doPost只有一種
- form中method屬性為post
- doGet有四種:
-
數(shù)據(jù)傳輸方式
- doGet方式:表單數(shù)據(jù)存放在URL地址后面。所有g(shù)et方式提交時(shí)HTTP中沒有消息體
- doPost方式:表單數(shù)據(jù)存放在HTTP協(xié)議的消息體中以實(shí)體的方式傳送到服務(wù)器
-
服務(wù)器獲取數(shù)據(jù)方式
- doGet方式:服務(wù)器采用request.QueryString來獲取變量的值
- doPost方式:服務(wù)器采用request.Form來獲取數(shù)據(jù)
-
傳送的數(shù)據(jù)量
- doGet:數(shù)據(jù)量長(zhǎng)度有限制掐暮,一般不超過2kb蝎抽。因?yàn)槭菂?shù)傳遞,且在地址欄中路克,故數(shù)據(jù)量有限制
- doPost:適合大規(guī)模的數(shù)據(jù)傳送樟结。因?yàn)槭且詫?shí)體的方式傳送的养交。
-
安全性
- doGet:安全性差。因?yàn)槭侵苯訉?shù)據(jù)顯示在地址欄中瓢宦,瀏覽器有緩沖碎连,可記錄用戶信息。所以安全性低
- doPost:安全性高驮履。因?yàn)閜ost方式提交數(shù)據(jù)時(shí)是采用的HTTP post機(jī)制鱼辙,是將表單中的字段與值放置在HTTP HEADER內(nèi)一起傳送到ACTION所指的URL中,用戶是看不見的
在做數(shù)據(jù)查詢時(shí)玫镐,建議用Get方式倒戏;而在做數(shù)據(jù)添加、修改或刪除時(shí)摘悴,建議用Post方式
五峭梳、使用IEDA開發(fā)Servlet
- 準(zhǔn)備Servlet需要的jar包
- 在IEDA中新建一個(gè)Web項(xiàng)目
- 新建一個(gè)Servlet
- 編寫代碼
- 配置web.xml中Servlet的servlet和servlet-mapping
- 啟動(dòng)Tomcat服務(wù)器
- 訪問Servlet編寫的網(wǎng)頁(yè)
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServletTest03 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello Servlet</h1>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
配置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>Test03</servlet-name>
<servlet-class>com.kuang.servlet.ServletTest03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test03</servlet-name>
<url-pattern>/aaa</url-pattern>
</servlet-mapping>
</web-app>
啟動(dòng)服務(wù)器發(fā)布后:
注意:一般情況下一個(gè)URL對(duì)應(yīng)一個(gè)請(qǐng)求
六、Response——重定向
當(dāng)文檔移動(dòng)到新的位置蹂喻,我們需要向客戶端發(fā)送這個(gè)新位置時(shí)葱椭,我們需要用到網(wǎng)頁(yè)重定向。重定向請(qǐng)求到另一個(gè)網(wǎng)頁(yè)的最簡(jiǎn)單的方式是使用 response 對(duì)象的 sendRedirect(String s) 方法口四,參數(shù)需傳遞新的網(wǎng)頁(yè)URL
注意:
-
使用sendRedirect(String s) 方法時(shí)孵运,若想跳轉(zhuǎn)到本服務(wù)器下的其他頁(yè)面,則傳入該頁(yè)面的URL蔓彩,重定向后地址欄最后的URL值會(huì)改變
例如重定向到本服務(wù)器的404.jsp時(shí):
response.sendRedirect("404.jap");
-
使用sendRedirect(String s) 方法跳轉(zhuǎn)到其他服務(wù)器的頁(yè)面時(shí)治笨,直接傳入新頁(yè)面的完整網(wǎng)址,包括HTTP或HTTPS協(xié)議赤嚼,否則將重定向失敗
例如需要重定向到百度首頁(yè)時(shí):
response.sendRedirect("https://www.baidu.com");
七旷赖、Response——ServletContext
Web容器在啟動(dòng)時(shí),它會(huì)為每一個(gè)Web應(yīng)用程序創(chuàng)建一個(gè)對(duì)應(yīng)的ServletContext對(duì)象更卒,它代表當(dāng)前對(duì)象的引用
-
通過ServletContext對(duì)象實(shí)現(xiàn)數(shù)據(jù)共享
在這里插入圖片描述
發(fā)送端:
import javax.servlet.ServletContext;
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 java.io.IOException;
@WebServlet(name = "ServletDemo03")
public class ServletDemo03 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通過Servlet對(duì)象可獲取一個(gè)ServletContext對(duì)象
ServletContext servletContext = this.getServletContext();
String name = "華為";
//通過setAttribute方法向ServletContext發(fā)送數(shù)據(jù)
servletContext.setAttribute("name",name);
response.setCharacterEncoding("utf-8");
response.getWriter().print("設(shè)置name成功:"+name);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
接收端:
import javax.servlet.ServletContext;
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 java.io.IOException;
@WebServlet(name = "ServletDemo04")
public class ServletDemo04 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//通過getAttribute方法向ServletContext接收數(shù)據(jù)
Object name = servletContext.getAttribute("name");
response.setCharacterEncoding("utf-8");
response.getWriter().println("接收到的name:"+name);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
-
通過ServletContext讀取網(wǎng)站配置文件
- 新建一個(gè)properties文件
driver=com.mysql.jdbc.Driver username=root password=123456 url=jdbc:mysql://localhost:3306/smbms
- 編寫Servlet類
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; //讀取properties配置文件 public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //讀取配置文件 //1.獲得配置文件的路徑 String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/resources/database.properties"); System.out.println("取得的路徑為:"+realPath); Properties properties = new Properties(); FileInputStream is = new FileInputStream(realPath); properties.load(is);//把文件流加載到配置文件的對(duì)象中等孵; String driver = properties.getProperty("driver"); String username = properties.getProperty("username"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); //響應(yīng)到網(wǎng)頁(yè) resp.getWriter().println(driver); resp.getWriter().println(username); resp.getWriter().println(password); resp.getWriter().println(url); } }
- 配置web.xml
- 訪問
注意:配置文件路徑在src下(在src下新建resources文件夾)!u蹇铡俯萌!
八、簡(jiǎn)單驗(yàn)證碼的實(shí)現(xiàn)
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
//驗(yàn)證碼
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//自動(dòng)刷新網(wǎng)頁(yè):---> refresh 刷新網(wǎng)頁(yè)上枕, 2時(shí)間
resp.setHeader("refresh","2");
//驗(yàn)證碼是一個(gè)圖片 咐熙, 我們需要制作一個(gè)圖片
BufferedImage image = new BufferedImage(100,30,BufferedImage.TYPE_3BYTE_BGR);
//圖片寫入一些東西
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.red);
String num = String.valueOf(newRandom());
graphics.drawString(num,10,10);
//想辦法讓瀏覽器知道我們給的是一張圖片
resp.setContentType("image/jpg");
//讓網(wǎng)站去打開圖片
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成隨機(jī)數(shù)
public int newRandom(){
int num = (int) Math.ceil(Math.random()*10000);
return num;
}
}
九、Request——獲取項(xiàng)目信息
-
jsp獲取項(xiàng)目路徑
${pageContext.request.contextPath}
-
Request對(duì)象
Request對(duì)象代表客戶端的請(qǐng)求辨萍,當(dāng)客戶端通過HTTP協(xié)議訪問服務(wù)器時(shí)棋恼,HTTP請(qǐng)求頭中的所有信息都封裝在這個(gè)對(duì)象中,通過這個(gè)對(duì)象提供的方法,可以獲得客戶端請(qǐng)求的所有信息蘸泻。
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RequestDemo01 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //查看request對(duì)象的方式 System.out.println(request.getContextPath()); //獲得web項(xiàng)目路徑 System.out.println(request.getRequestURI()); //請(qǐng)求的URL路徑 //Remote 遠(yuǎn)程 System.out.println(request.getRemoteUser()); //獲得遠(yuǎn)程的用戶名 System.out.println(request.getRequestedSessionId()); //獲得SessionId琉苇; System.out.println(request.getServletPath()); //請(qǐng)求servlet的url System.out.println(request.getLocalAddr()); //獲得本地地址 防火墻 System.out.println(request.getLocalName()); //獲得本地名字 System.out.println(request.getLocalPort()); //獲得訪問的端口號(hào) } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
十、Request——接收前端用戶提交的數(shù)據(jù)&請(qǐng)求轉(zhuǎn)發(fā)
-
登錄頁(yè)面jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登錄</title> </head> <body> <h1>登錄</h1> <form action="${pageContext.request.contextPath}/a" method="post"> <p>用戶名:<input type="text" name="username"></p> <p>密碼:<input type="password" name="password"></p> <p> <input type="submit"> <input type="reset"> </p> </form> </body> </html>
-
成功頁(yè)面jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登錄成功</title> </head> <body> <h1>登錄成功</h1> </body> </html>
-
接收前端傳遞的控件信息:request.getParameter(“控件的name‘)悦施;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RequestDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //處理亂碼 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); if (username.equals("admin") && password.equals("123456")){ System.out.println("登陸成功"); //轉(zhuǎn)發(fā) //轉(zhuǎn)發(fā):服務(wù)器把這個(gè)請(qǐng)求轉(zhuǎn)向另外一個(gè)Servlet去處理并扇; (地址欄不會(huì)變) //RequestDispatcher ,需要使用RequestDispatcher來進(jìn)行處理,我們需要獲得這個(gè)類抡诞,參數(shù)為要轉(zhuǎn)發(fā)到的頁(yè)面 req.getRequestDispatcher("/page/success.jsp").forward(req,resp); }else { System.out.println("登陸失敗"); } } }
- 轉(zhuǎn)發(fā)
- 通過ServletContext的getRequestDispatcher(String path)方法穷蛹,該方法返回一個(gè)RequestDispatcher對(duì)象,調(diào)用這個(gè)對(duì)象的forward方法可以實(shí)現(xiàn)請(qǐng)求轉(zhuǎn)發(fā)昼汗。
- 通過request對(duì)象提供的getRequestDispatche(String path)方法肴熏,該方法返回一個(gè)RequestDispatcher對(duì)象,調(diào)用這個(gè)對(duì)象的forward方法可以實(shí)現(xiàn)請(qǐng)求轉(zhuǎn)發(fā)
十一顷窒、轉(zhuǎn)發(fā)和重定向的區(qū)別
- 重定向:服務(wù)器告訴客戶端去請(qǐng)求另外一個(gè)地址蛙吏,屬于客戶端行為,地址欄會(huì)改變鞋吉,不能攜帶參數(shù)(302)
- 轉(zhuǎn)發(fā):服務(wù)器自己轉(zhuǎn)發(fā)到服務(wù)器上的另一個(gè)請(qǐng)求鸦做,屬于服務(wù)器行為,地址欄不會(huì)變谓着,可以攜帶參數(shù)(307)
十二泼诱、會(huì)話
-
概念
在Web中,會(huì)話表示從瀏覽器打開某個(gè)網(wǎng)站赊锚,在這個(gè)網(wǎng)站中無論操作了什么治筒,直到關(guān)閉瀏覽器,這一個(gè)過程舷蒲,稱之為一個(gè)會(huì)話耸袜。
-
怎樣算會(huì)話結(jié)束
- 客戶端關(guān)閉了
- 服務(wù)器銷毀了
-
為什么要處理會(huì)話
長(zhǎng)期保持會(huì)話,無論用戶關(guān)閉多少次瀏覽器牲平,這個(gè)會(huì)話都存在(如虎牙的一個(gè)月免登錄)
-
保存會(huì)話的兩種機(jī)制
-
Cookie:
Cookie是客戶端機(jī)制句灌,程序把每個(gè)用戶的數(shù)據(jù)以cookie的形式寫給用戶各自的瀏覽器。當(dāng)用戶使用瀏覽器再去訪問服務(wù)器中的web資源時(shí)欠拾,就會(huì)帶著各自的數(shù)據(jù)去。這樣骗绕,web資源處理的就是用戶各自的數(shù)據(jù)了
好比超市給用戶的會(huì)員卡藐窄,下次帶去就知道之前來過
-
Session
Session是服務(wù)器端技術(shù),利用這個(gè)機(jī)制酬土,服務(wù)器在運(yùn)行時(shí)可以為每一個(gè)用戶的瀏覽器創(chuàng)建一個(gè)其獨(dú)享的session對(duì)象荆忍,由于session為用戶瀏覽器獨(dú)享,所以用戶在訪問服務(wù)器的web資源時(shí),可以把各自的數(shù)據(jù)放在各自的session中刹枉,當(dāng)用戶再去訪問服務(wù)器中的其它web資源時(shí)叽唱,其它web資源再?gòu)挠脩舾髯缘膕ession中取出數(shù)據(jù)為用戶服務(wù)。
好比超市在自己的系統(tǒng)上保存了用戶的信息微宝,用戶下次去直接說會(huì)員名就行
-
十三棺亭、Cookie
構(gòu)造器:
Cookie cookie = new Cookie(String name,String value);
服務(wù)器響應(yīng)Cookie給客戶端:
response.addCookie(Cookie);
服務(wù)器查看用戶帶來的請(qǐng)求是否有Cookie
Cookie[] cookies = Request.getCookie();
//可以使用cookie來驗(yàn)證用戶是否來過
//判斷cookies是否為空,然后遍歷即可
Cookie.getName();
Cookie.getValue();
No. | 方法 | 類型 | 描述 |
---|---|---|---|
1 | Cookie(String name, String value) | 構(gòu)造方法 | 實(shí)例化Cookie對(duì)象蟋软,傳入cooke名稱和cookie的值 |
2 | public String getName() | 普通方法 | 取得Cookie的名字 |
3 | public String getValue() | 普通方法 | 取得Cookie的值 |
4 | public void setValue(String newValue) | 普通方法 | 設(shè)置Cookie的值 |
5 | public void setMaxAge(int expiry) | 普通方法 | 設(shè)置Cookie的最大保存時(shí)間镶摘,即cookie的有效期,當(dāng)服務(wù)器給瀏覽器回送一個(gè)cookie時(shí)岳守,如果在服務(wù)器端沒有調(diào)用setMaxAge方法設(shè)置cookie的有效期凄敢,那么cookie的有效期只在一次會(huì)話過程中有效,用戶開一個(gè)瀏覽器湿痢,點(diǎn)擊多個(gè)超鏈接涝缝,訪問服務(wù)器多個(gè)web資源,然后關(guān)閉瀏覽器譬重,整個(gè)過程稱之為一次會(huì)話拒逮,當(dāng)用戶關(guān)閉瀏覽器,會(huì)話就結(jié)束了害幅,此時(shí)cookie就會(huì)失效消恍,如果在服務(wù)器端使用setMaxAge方法設(shè)置了cookie的有效期,比如設(shè)置了30分鐘以现,那么當(dāng)服務(wù)器把cookie發(fā)送給瀏覽器時(shí)狠怨,此時(shí)cookie就會(huì)在客戶端的硬盤上存儲(chǔ)30分鐘,在30分鐘內(nèi)邑遏,即使瀏覽器關(guān)了佣赖,cookie依然存在,在30分鐘內(nèi)记盒,打開瀏覽器訪問服務(wù)器時(shí)憎蛤,瀏覽器都會(huì)把cookie一起帶上,這樣就可以在服務(wù)器端獲取到客戶端瀏覽器傳遞過來的cookie里面的信息了纪吮,這就是cookie設(shè)置maxAge和不設(shè)置maxAge的區(qū)別俩檬,不設(shè)置maxAge,那么cookie就只在一次會(huì)話中有效碾盟,一旦用戶關(guān)閉了瀏覽器棚辽,那么cookie就沒有了,那么瀏覽器是怎么做到這一點(diǎn)的呢冰肴,我們啟動(dòng)一個(gè)瀏覽器屈藐,就相當(dāng)于啟動(dòng)一個(gè)應(yīng)用程序榔组,而服務(wù)器回送的cookie首先是存在瀏覽器的緩存中的,當(dāng)瀏覽器關(guān)閉時(shí)联逻,瀏覽器的緩存自然就沒有了搓扯,所以存儲(chǔ)在緩存中的cookie自然就被清掉了,而如果設(shè)置了cookie的有效期包归,那么瀏覽器在關(guān)閉時(shí)锨推,就會(huì)把緩存中的cookie寫到硬盤上存儲(chǔ)起來,這樣cookie就能夠一直存在了箫踩。 |
6 | public int getMaxAge() | 普通方法 | 獲取Cookies的有效期 |
7 | public void setPath(String uri) | 普通方法 | 設(shè)置cookie的有效路徑爱态,比如把cookie的有效路徑設(shè)置為"/xdp",那么瀏覽器訪問"xdp"目錄下的web資源時(shí)境钟,都會(huì)帶上cookie锦担,再比如把cookie的有效路徑設(shè)置為"/xdp/gacl",那么瀏覽器只有在訪問"xdp"目錄下的"gacl"這個(gè)目錄里面的web資源時(shí)才會(huì)帶上cookie一起訪問慨削,而當(dāng)訪問"xdp"目錄下的web資源時(shí)洞渔,瀏覽器是不帶cookie的 |
8 | public String getPath() | 普通方法 | 獲取cookie的有效路徑 |
9 | public void setDomain(String pattern) | 普通方法 | 設(shè)置cookie的有效域 |
10 | public String getDomain() | 普通方法 | 獲取cookie的有效域 |
Cookie測(cè)試用戶是否來過
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieDemo extends HttpServlet {
Cookie cookie = null;
Boolean flag = false;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Cookie[] cookies = req.getCookies();
if (flag){
resp.getWriter().println("上次登錄時(shí)間為"+ cookie.getValue());
resp.getWriter().println("刷新了Cookie");
}else {
resp.getWriter().println("第一次來沒有Cookie");
}
cookie = new Cookie("LastLoginTime",System.currentTimeMillis()+"");
resp.addCookie(cookie);
flag=true;
}
}
十四、Session
- 只要客戶端一旦連接上服務(wù)器缚态,服務(wù)器就會(huì)自動(dòng)產(chǎn)生Session磁椒,一個(gè)連接對(duì)應(yīng)一個(gè)session,session可以在一個(gè)會(huì)話中傳遞信息
- 通過setAttribute設(shè)置值
- 通過getAttribute獲得值
- Session由服務(wù)器控制玫芦,如果服務(wù)器重啟了浆熔,信息就會(huì)丟失
使用Session存入值:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//session由服務(wù)器創(chuàng)建
//得到的session對(duì)象
HttpSession session = req.getSession();
String id = session.getId();
resp.getWriter().println("獲得的sessionId"+id);
String name = "小學(xué)生";
session.setAttribute("name",name);
resp.getWriter().println("設(shè)置session成功:"+name);
}
}
獲取Session存入的值:
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;
import java.io.IOException;
@WebServlet(name = "SessionDemo2")
public class SessionDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String name = (String)session.getAttribute("name");
response.getWriter().println("得到的session信息:"+name);
//銷毀session
session.invalidate();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
- 會(huì)話注銷的方式一
session.invalidate();//通過代碼注銷會(huì)話
- 會(huì)話注銷的方式二
<!--session-config可以設(shè)置會(huì)話自動(dòng)過期,時(shí)間分鐘為單位-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>