- Servlet 實(shí)現(xiàn)原理
Servlet接口使Servlet容器能將Servlet類(lèi)載入內(nèi)存,并在Servlet實(shí)例上調(diào)用具體的方法. - Servlet的生命周期
Servlet進(jìn)入Servlet容器后調(diào)用其生命周期方法,分別是:- init:當(dāng)Servlet第一次被請(qǐng)求時(shí),Servlet會(huì)調(diào)用此方法,此方法只會(huì)被調(diào)用一次,后續(xù)請(qǐng)求中不會(huì)再次調(diào)用.調(diào)用此方法會(huì)將ServletConfig賦予類(lèi)級(jí)變量.
- Service:每次請(qǐng)求Servlet時(shí),都會(huì)調(diào)用次方法
- destroy:銷(xiāo)毀Servlet時(shí)調(diào)用
- Servlet的會(huì)話管理
包含URL重寫(xiě),隱藏域,Cookies,HttpSession四種 - URL重寫(xiě)
使用html 的a標(biāo)簽,將信息添加至URL上
<a href='?city=london'>London</a>
- 隱藏域
隱藏域的保持狀態(tài)與URL重寫(xiě)類(lèi)似,但它不是將值附加到URL上,而是將值放入HTML的隱藏域中,跟隨其他顯示表示的信息一起通過(guò)表單方式提交
<form method='post' action='update'>
<input type='hidden' name='id' value='1'>
<!--顯示信息省略-->
<input type="submit" value="提交">
URL重寫(xiě)與隱藏域只適用于無(wú)須跨越太多頁(yè)面的信息.
- Cookies
Cookies可以幫助我們?cè)诙囗?yè)面之間很好的會(huì)話,瀏覽器通常支持每個(gè)網(wǎng)站高達(dá)20個(gè)Cookies
Cookies的創(chuàng)建:
Cookie cookie=new Cookie(name,value);
Cookie cookie=new Cookie("user","admin");
將cookie發(fā)送至瀏覽器,使用HttpServletResponse的add方法:
httpServletResponse.addCookie(cookie);
- Cookies的信息獲取與刪除
Cookies信息獲取
在Servlet中并沒(méi)有g(shù)etCookieByName來(lái)簡(jiǎn)化獲取信息的工作,只能遍歷Cookie
- Cookies的信息獲取與刪除
Cookie cookies=request.getCookies();
Cookie cookie=null;
if(cookies!=null){
for(Cookie cookieCopy:cookies){
if(cookie.getName().equals("user")){
cookie=cookieCopy;
break;
}
}
}
Cookie刪除
使用JavaScript也可以創(chuàng)建和刪除cookie,詳情Google
cookie無(wú)法直接刪除,只能重新命名一個(gè)相同名字的cookie然后將其MaxAge設(shè)置為0
Cookie cookie=new Cookie("userName","");
cookie.setMaxAge(0);
response.addCookie(cookie);
- HttpSession
- 在所用會(huì)話追蹤技術(shù)中HttpSession是最強(qiáng)大也是最通用的.HttpSession在對(duì)象第一次訪問(wèn)網(wǎng)站時(shí)創(chuàng)建,用戶可以根據(jù)HttpServletRequest的getSession()方法獲取
HttpSession session=httpServletRequest.getSession();
- HttpSession存儲(chǔ)于內(nèi)存之中,因此盡量不要在其存儲(chǔ)大量數(shù)據(jù),要將數(shù)據(jù)存儲(chǔ)于HttpSession之中,使用其setAttribute()方法,獲取數(shù)據(jù)較Cookies簡(jiǎn)單,直接使用getAttribute(name)
- 在所用會(huì)話追蹤技術(shù)中HttpSession是最強(qiáng)大也是最通用的.HttpSession在對(duì)象第一次訪問(wèn)網(wǎng)站時(shí)創(chuàng)建,用戶可以根據(jù)HttpServletRequest的getSession()方法獲取
session.setAttribute(name,value);//存儲(chǔ)數(shù)據(jù)
session.getAttribute(name);//獲取數(shù)據(jù)
- 當(dāng)忘記存儲(chǔ)于session中的數(shù)據(jù)名字,可以使用getAttributeNames獲取,其返回一個(gè)Enumeration<String>對(duì)象可供迭代訪問(wèn)保存在session中的值
- 對(duì)于HttpSession由于是存儲(chǔ)于內(nèi)存中,過(guò)多會(huì)導(dǎo)致系統(tǒng)運(yùn)行不流暢,所以Java提供了HttpSession的過(guò)期屬性.
1.當(dāng)?shù)竭_(dá)一定時(shí)間未訪問(wèn)此session屬性后,系統(tǒng)將使會(huì)話過(guò)期,并清空其保存的對(duì)象,設(shè)置時(shí)長(zhǎng)使用getMaxInactiveInterval(int second).如果將second設(shè)置為0,session將永不過(guò)期,直到servlet容器關(guān)閉.
- 強(qiáng)制關(guān)閉session,清空所有數(shù)據(jù),使用invalidate方法