资源描述:
《servlet课程笔记(自己整理)》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
说明:根据蓝色字体索引,红色字体为重要Cookie相当于一对键值对(String–String),Session相当于一个集合类:ArrayList等,Session.setAttribute(String,Object)ServletRequest(接口)àHttpServletRequest(接口)ServletResponse(接口)àHttpServletResponse(接口)把servlet-api.jar文件放在C:ProgramFilesJavajdk1.6.0_10lib目录下/////cookie操作importjavax.servlet.http.*;importjava.io.*;publicclassCookieTest1extendsHttpServlet{publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres){res.setContentType("text/html;charset=gbk");PrintWriterpw=res.getWriter();//1.先在服务器端创建一个cookieCookiemyCookie=newCookie("color1","red");//2.该cookie存在的时间,SetsthemaximumageofthecookieinsecondsmyCookie.setMaxAge(30);//如果你不设置存在时间,那么该cookie将不会保存//3.将该cookie写回到客户端res.addCookie(myCookie);pw.println("已经创建了cookie");}}-------------------------------------------------------------------------------------------------Servlet跳转当然,在servlet中,一般跳转都发生在doGet,doPost等方法里面。1) redirect方式response.sendRedirect("/a.jsp");页面的路径是相对路径。sendRedirect可以将页面跳转到任何页面,不一定局限于本web应用中,如:response.sendRedirect("URL");跳转后浏览器地址栏变化。 这种方式要传值出去的话,只能在url中带parameter或者放在session中,无法使用request.setAttribute来传递。2)forward方式RequestDispatcherdispatcher=request.getRequestDispatcher("/a.jsp");dispatcher.forward(request,response);Servlet页面跳转的路径是相对路径。forward方式只能跳转到本web应用中的页面上。跳转后浏览器地址栏不会变化。使用这种方式跳转,传值可以使用三种方法:url中带parameter,session,request.setAttribute-------------------------------------------------------------------------------------------------//如何创建cookie案例//1.现在服务器端创建一个cookieCookiemyCookie=newCookie("color1","red");//2.该cookie存在的时间myCookie.setMaxAge(30);//如果你不设置存在时间,那么该cookie将不会保存,“秒”//3.将该cookie写回到客户端res.addCookie(myCookie);-------------------------------------------------------------------------------------------------//如何读取cookie案例Cookie[]allCookies=req.getCookies();inti=0;//如果allCookies不为空...if(allCookies!=null){//从中取出cookiefor(i=0;i删除用户");//分页处理,提交给本页if(pageNow!=1)pw.println("上一页");-------------------------------------------------------------------------------------------------//向servletcontext中添加属性//1得到servletcontextServletContextsc=this.getServletContext();//相当于jsp中application上面的this指的是HttpServlet,继承自GenericServlet,它有getServletContext()方法//2添加属性sc.setAttribute("myInfo","我是顺平");//比较session,添加一个sessionHttpSessionhs=req.getSession(true);hs.setAttribute("test","中国人");//安装tomcat默认的时间是30分钟//当然也可以conf目录下的web.xml文件中自己设置时间hs.setMaxInactiveInterval(60*3);//seconds //当然也可以在servletcontext中放入一个对象//CatmyCat=newCat("小明",30);//sc.setAttribute("cat1",myCat);-------------------------------------------------------------------------------------------------//从servletcontext中得到属性//1得到servletcontextServletContextsc=this.getServletContext();//2得到属性和它对应的值Stringinfo=(String)sc.getAttribute("myInfo");//从session中得到属性HttpSessionhs=req.getSession(true);Stringval=(String)hs.getAttribute("test");//得到另外一个属性//CatmyCat=(Cat)sc.getAttribute("cat1");//pw.println("从servletcontext中得到属性cat1他的名字是"+//myCat.getName()+"他的年龄是"+myCat.getAge()+"
");-------------------------------------------------------------------------------------------------//session案例---如何删除属性/如何使得session无效//得到和req相关联的session,如果没有就创建sessionHttpSessionht=req.getSession(true);//向session中添加一个属性(String类型的)ht.setAttribute("you","周星星");ht.setAttribute("he","刘德华");pw.println("在没有删除you属性前you的值="+ht.getAttribute("you")+"
");//从session中删除you属性//ht.removeAttribute("you");ht.setMaxInactiveInterval(0);//session永远不失效??若setMaxInactiveInterval设置为负值,则表示////该Session永不过期pw.println("删除you属性后you的值="+ht.getAttribute("you")+"
");pw.println("删除you属性后he的值="+ht.getAttribute("he")+"
"); jsp中,用publicvoidinvalidate()方法使session失效(手工)-------------------------------------------------------------------------------------------------//隐藏表单案例--提交界面pw.println("
");//隐藏表单案例--接收数据//得到隐藏的性别值Stringsex=req.getParameter("sex");-------------------------------------------------------------------------------------------------//这是我的第一个Serlvet,使用实现servlet接口的方式来开发importjavax.servlet.*;importjava.io.*;importjavax.servlet.Servlet;importjava.io.IOException;publicclassHelloimplementsServlet{//该函数用于初始化该serlvet(类似于类的构造函数)//该函数只会被调用一次(当用户第一次访问该servlet时被调用)publicvoidinit(ServletConfigparm1)throwsServletException{}publicServletConfiggetServletConfig(){}publicvoidservice(ServletRequestreq,ServletResponseres)throwsServletException,IOException{}publicStringgetServletInfo(){}publicvoiddestroy(){}}-------------------------------------------------------------------------------------------------//这是第二种开发servlet的方法(继承GenericServlet开发)importjavax.servlet.GenericServlet;importjavax.servlet.*;importjava.io.*;publicclassHelloGenextendsGenericServlet{//重写service方法即可publicvoidservice(ServletRequestreq,ServletResponseres){}} -------------------------------------------------------------------------------------------------//在servlet中操作文件,跟java中一样,其实servlet就是一个Java类//写操作FilemyFile=newFile("d:\count.txt");//FileWriterfw=newFileWriter(myFile);//BufferedWriterbr=newBufferedWriter(fw);//br.write("1");//br.close();//fw.close();//读操作res.setContentType("text/html;charset=gbk");PrintWriterpw=res.getWriter();FileReaderfr=newFileReader("d:\count.txt");BufferedReaderbr=newBufferedReader(fr);Stringkk=br.readLine();pw.println("times="+kk);-------------------------------------------------------------------------------------------------pw.println("修改用户 | ");-------------------------------------------------------------------------------------------------webApplication的概念1、webApplicationName1、WEB-INFweb.xml该webapp的配置文件lib该webapp用到的库文件classes存放编译好的servlet2、META-INF存放该webapp的上下文信息,符合J2EE标准2、WebApplication可以直接放在webapps下面3、也可以通过配置文件指定到其他目录里面如:D:Tomcat6confserver.xml文件中配置:Tomcat的目录结构bin/二进制可执行文件和脚本 catalinastartstopcatalinadebugrunexitcommon/Catalina本身和web应用可加载的类目录conf/配置文件目录logs/日志目录server/服务器所需的类库目录shared/WebApp共享的类库webapps/Web应用所存放的目录applicationswork/Tomcat的工作目录(存放jsp产生的class文件)temp/存放临时产生的文件创建Servlet1、XXXextendsHttpServlet2、OverridedoGetdoPost(重写方法)3、copytoWEB-INF/classes4、web.xml1、例子:HelloWorldServletHelloWorldServlet2、HelloWorldServlet/HelloWorldServlet注意:webapp根路径(url)必须/开头5、restartserverServlet的生命周期生命全过程:加载ClassLoader实例化new初始化init(ServletConfig)处理请求servicedoGetdoPost退出服务destroy()只有一个对象API中的过程:init()//只执行一次,第一次初始化的时候publicvoidinit(ServletConfigconfig)throwsServletExceptionservice()publicvoidservice(ServletRequestreq,ServletResponseres)throwsServletException,java.io.IOException destroy()//webapp退出的时候publicvoiddestroy()initinit(servletconfigconfig)this.config=configinit();重写必须得super.init(config)不然不能使用this.getServletConfig当然也就不能用getInitParameter();我们只需要重写init();Servlet编程接口GenericServlet是所有Servlet的鼻祖用于HTTP的Servlet编程都通过继承javax.servlet.http.HttpServlet实现请求处理方法:(分别对应http协议的7种请求)1、doGet响应Get请求,常用2、doPost响应Post请求,常用3、doPut用于http1.1协议4、doDelete用于http1.1协议5、doHead仅响应Get请求的头部。6、doOptions用于http1.1协议7、doTrace用于http1.1协议实例的个数:在非分布的情况下,通常一个Servlet在服务器中有一个实例获取表单信息通过HttpServletRequest的getParameter()方法来获得客户端传递过来的数据getParameter()方法返回一个字符串类型的值getParameterNames()返回Enumeration类型的值,getParameterValues()返回一个字符串数组Web上保持状态的手段:cookiesessionapplicationpersistence处理CookieHttp协议的无连接性要求出现一种保存C/S间状态的机制Cookie:保存到客户端的一个文本文件,与特定客户相关Cookie以“名-值”对的形式保存数据创建Cookie:newCookie(name,value)可以使用Cookie的setXXX方法来设定一些相应的值setName(Stringname)/getName()setValue(Stringvalue)/getValue()setMaxAge(intage)/getMaxAge()利用HttpServletResponse的addCookie(Cookie)方法将它设置到客户端 利用HttpServletRequest的getCookies()方法来读取客户端的所有Cookie,返回一个Cookie数组设置CookieSetCookies.java读取CookieShowCookies.java1:服务器可以向客户端写内容2:只能是文本内容3:客户端可以阻止服务器写入4:只能拿自己webapp写入的东西5:Cookie分为两种属于窗口/子窗口(放在内存中的)属于文本(有生命周期的)6:一个servlet/jsp设置的cookies能够被同一个路径下面或者子路径下面的servlet/jsp读到(路径=URL)(路径!=真实文件路径)会话跟踪(session)Session在某段时间一连串客户端与服务器端的“交易”在Jsp/Servlet中,如果浏览器不支持Cookie,可以通过URL重写来实现,就是将一些额外数据追加到表示会话的每个URL末尾,服务器在该标示符与其存储的有关的该会话的数据之间建立关联。如hello.jsp?jsessionid=1234可以通过程序来终止一个会话。如果客户端在一定时间内没有操作,服务器会自动终止会话。通过HttpSession来读写Session规则如果浏览器支持Cookie,创建Session的时候会把SessionID保存在Cookie里如果不支持Cookie,必须自己编程使用URL重写的方式实现Sessionresponse.encodeURL()转码URL后面加入SessionIdSession不象Cookie拥有路径访问的问题同一个application下的servlet/jsp可以共享同一个session,前提是同一个客户端窗口.?HttpServletRequest中的Session管理方法getRequestedSessionId():返回随客户端请求到来的会话ID。可能与当前的会话ID相同,也可能不同。getSession(booleanisNew):如果会话已经存在,则返回一个HttpSession,如果不存在并且isNew为true,则会新建一个HttpSessionisRequestedSessionIdFromCookie():当前的SessionID如果是从Cookie获得,为trueisRequestedSessionIdFromURL():当前SessionID如果是由URL获得,为true isRequestedSessionIdValid():如果客户端的会话ID代表的是有效会话,则返回true。否则(比如,会话过期或根本不存在),返回falseHttpSession的常用方法getAttributeNames()/getAttribute()getCreateTime()getId()getMaxInactiveInterval()invalidate()isNew()setAttribute()setMaxInactivateInterval()Session总结(一个对象)1、服务器的一块内存(存key-value)2、和客户端窗口对应(子窗口)(独一无二)3、客户端和服务器有对应的SessionID4、客户端向服务器端发送SessionID的时候两种方式:5、cookie(内存cookie)6、rewritenURL7、浏览器禁掉cookie,就不能使用session(使用cookie实现的session)8、如果想安全的使用session(不论客户端是否禁止cookie),只能使用URL重写(大大增加编程负担),所以很多网站要求客户端打开cookieApplication用于保存整个WebApplication的生命周期内都可以访问的数据在API中表现为ServletContext通过HttpServlet的getServletContext方法可以拿到getServletContextfoundin:javax.servlet.FilterConfig.getServletContext()javax.servlet.http.HttpSession.getServletContext()javax.servlet.ServletConfig.getServletContext()javax.servlet.GenericServlet.getServletContext()javax.servlet.ServletContextEvent.getServletContext()通过ServletCon489bute方法取得/设置相关属性TestServletContext.javaservlet中的请求转发RequestDispatcher接口对象允许将请求转发到其他服务器资源通过RequestDispatcher的forward(HttpServletRequest,HttpServletResponse)方法可以将请求转发通过ServletContext的getRequestDispatcher(Stringurl)方法来获得RequestDispatcher对象,并且指定转发的目标url资源可以通过HttpServletRequest的setAttribute(Stringname,Stringvalue)来设置需要传递的参数,然后在代理servlet中就可以 使用HttpServerRequest的getAttribute(Stringname)来获得对应的值另外一种:HttpServletResponse.sendRedirect(java.lang.String location)数据库处理以及在Servlet中使用Bean广义javabean=普通java类狭义javabean=符合SunJavaBean标准的类在Servlet中使用Bean和在通常程序中使用Bean类似属性名称第一个字母必须小写,一般private,比如:privateproductId一般具有gettersandsetters要具有一个参数为空的构造方法但Bean不应具有GUI表现一般是用来实现某一业务逻辑或取得特定结果 CookiepublicclassCookieextendsjava.lang.Objectimplementsjava.lang.CloneablepublicclassCookieextendsjava.lang.Objectimplementsjava.lang.CloneableCreatesacookie,asmallamountofinformationsentbyaservlettoaWebbrowser,savedbythebrowser,andlatersentbacktotheserver.Acookie'svaluecanuniquelyidentifyaclient,socookiesarecommonlyusedforsessionmanagement.Acookiehasaname,asinglevalue,andoptionalattributessuchasacomment,pathanddomainqualifiers,amaximumage,andaversionnumber.SomeWebbrowsershavebugsinhowtheyhandletheoptionalattributes,sousethemsparinglytoimprovetheinteroperabilityofyourservlets.TheservletsendscookiestothebrowserbyusingtheHttpServletResponse.addCookie(javax.servlet.http.Cookie)method,whichaddsfieldstoHTTPresponseheaderstosendcookiestothebrowser,oneatatime.Thebrowserisexpectedtosupport20cookiesforeachWebserver,300cookiestotal,andmaylimitcookiesizeto4KBeach.ThebrowserreturnscookiestotheservletbyaddingfieldstoHTTPrequestheaders.CookiescanberetrievedfromarequestbyusingtheHttpServletRequest.getCookies()method.Severalcookiesmighthavethesamenamebutdifferentpathattributes.CookiesaffectthecachingoftheWebpagesthatusethem.HTTP1.0doesnotcachepagesthatusecookiescreatedwiththisclass.ThisclassdoesnotsupportthecachecontroldefinedwithHTTP1.1.ThisclasssupportsboththeVersion0(byNetscape)andVersion1(byRFC2109)cookiespecifications.Bydefault,cookiesarecreatedusingVersion0toensurethebestinteroperability.ConstructorSummaryCookie(java.lang.String name,java.lang.String value) Constructsacookiewithaspecifiednameandvalue. MethodSummary java.lang.Objectclone() Overridesthestandardjava.lang.Object.clonemethodtoreturnacopyofthiscookie. java.lang.StringgetComment() Returnsthecommentdescribingthepurposeofthiscookie,ornullifthecookiehasnocomment. java.lang.StringgetDomain() Returnsthedomainnamesetforthiscookie. intgetMaxAge() Returnsthemaximumageofthecookie,specifiedinseconds,Bydefault,-1indicatingthecookiewillpersistuntilbrowsershutdown. java.lang.StringgetName() Returnsthenameofthecookie. java.lang.StringgetPath() Returnsthepathontheservertowhichthebrowserreturnsthiscookie. booleangetSecure() Returnstrueifthebrowserissendingcookiesonlyoverasecureprotocol,orfalseifthebrowsercansendcookiesusinganyprotocol. java.lang.StringgetValue() Returnsthevalueofthecookie. intgetVersion() Returnstheversionoftheprotocolthiscookiecomplieswith. voidsetComment(java.lang.String purpose) Specifiesacommentthatdescribesacookie'spurpose. voidsetDomain(java.lang.String pattern) Specifiesthedomainwithinwhichthiscookieshouldbepresented. voidsetMaxAge(int expiry) Setsthemaximumageofthecookieinseconds. voidsetPath(java.lang.String uri) Specifiesapathforthecookietowhichtheclientshouldreturnthecookie. voidsetSecure(boolean flag) Indicatestothebrowserwhetherthecookieshouldonlybesentusingasecureprotocol,suchasHTTPSorSSL. voidsetValue(java.lang.String newValue) Assignsanewvaluetoacookieafterthecookieiscreated. voidsetVersion(int v) Setstheversionofthecookieprotocolthiscookiecomplieswith.HttpServletRequestpublicabstractinterfaceHttpServletRequestextendsServletRequestTheservletcontainercreatesanHttpServletRequestobjectandpassesitasanargumenttotheservlet'sservicemethods(doGet,doPost,etc).MethodSummary java.lang.StringgetAuthType() Returnsthenameoftheauthenticationschemeusedtoprotecttheservlet. java.lang.StringgetContextPath() ReturnstheportionoftherequestURIthatindicatesthecontextoftherequest. Cookie[]getCookies() ReturnsanarraycontainingalloftheCookieobjectstheclientsentwiththisrequest. longgetDateHeader(java.lang.String name) Returnsthevalueofthespecifiedrequestheaderasalongvaluethat representsaDateobject. java.lang.StringgetHeader(java.lang.String name) ReturnsthevalueofthespecifiedrequestheaderasaString. java.util.EnumerationgetHeaderNames() Returnsanenumerationofalltheheadernamesthisrequestcontains. java.util.EnumerationgetHeaders(java.lang.String name) ReturnsallthevaluesofthespecifiedrequestheaderasanEnumerationofStringobjects. intgetIntHeader(java.lang.String name) Returnsthevalueofthespecifiedrequestheaderasanint. java.lang.StringgetMethod() ReturnsthenameoftheHTTPmethodwithwhichthisrequestwasmade,forexample,GET,POST,orPUT. java.lang.StringgetPathInfo() ReturnsanyextrapathinformationassociatedwiththeURLtheclientsentwhenitmadethisrequest. java.lang.StringgetPathTranslated() Returnsanyextrapathinformationaftertheservletnamebutbeforethequerystring,andtranslatesittoarealpath. java.lang.StringgetQueryString() ReturnsthequerystringthatiscontainedintherequestURLafterthepath. java.lang.StringgetRemoteUser() Returnstheloginoftheusermakingthisrequest,iftheuserhasbeenauthenticated,ornulliftheuserhasnotbeenauthenticated. java.lang.StringgetRequestedSessionId() ReturnsthesessionIDspecifiedbytheclient. java.lang.StringgetRequestURI() Returnsthepartofthisrequest'sURLfromtheprotocolnameuptothe querystringinthefirstlineoftheHTTPrequest. java.lang.StringBuffergetRequestURL() ReconstructstheURLtheclientusedtomaketherequest. java.lang.StringgetServletPath() Returnsthepartofthisrequest'sURLthatcallstheservlet. HttpSessiongetSession() Returnsthecurrentsessionassociatedwiththisrequest,oriftherequestdoesnothaveasession,createsone. HttpSessiongetSession(boolean create) ReturnsthecurrentHttpSessionassociatedwiththisrequestor,ififthereisnocurrentsessionandcreateistrue,returnsanewsession. java.security.PrincipalgetUserPrincipal() Returnsajava.security.Principalobjectcontainingthenameofthecurrentauthenticateduser. booleanisRequestedSessionIdFromCookie() CheckswhethertherequestedsessionIDcameinasacookie. booleanisRequestedSessionIdFromUrl() Deprecated. AsofVersion2.1oftheJavaServletAPI,useisRequestedSessionIdFromURL()instead. booleanisRequestedSessionIdFromURL() CheckswhethertherequestedsessionIDcameinaspartoftherequestURL. booleanisRequestedSessionIdValid() CheckswhethertherequestedsessionIDisstillvalid. booleanisUserInRole(java.lang.String role) Returnsabooleanindicatingwhethertheauthenticateduserisincludedinthespecifiedlogical"role".Methodsinheritedfrominterfacejavax.servlet.ServletRequest getAttribute,getAttributeNames,getCharacterEncoding,getContentLength,getContentType,getInputStream,getLocale,getLocales,getParameter,getParameterMap,getParameterNames,getParameterValues,getProtocol,getReader,getRealPath,getRemoteAddr,getRemoteHost,getRequestDispatcher,getScheme,getServerName,getServerPort,isSecure,removeAttribute,setAttribute,setCharacterEncodingHttpServletResponsepublicabstractinterfaceHttpServletResponseextendsServletResponseExtendstheServletResponseinterfacetoprovideHTTP-specificfunctionalityinsendingaresponse.Forexample,ithasmethodstoaccessHTTPheadersandcookies.TheservletcontainercreatesanHttpServletRequestobjectandpassesitasanargumenttotheservlet'sservicemethods(doGet,doPost,etc).MethodSummary voidaddCookie(Cookie cookie) Addsthespecifiedcookietotheresponse. voidaddDateHeader(java.lang.String name,long date) Addsaresponseheaderwiththegivennameanddate-value. voidaddHeader(java.lang.String name,java.lang.String value) Addsaresponseheaderwiththegivennameandvalue. voidaddIntHeader(java.lang.String name,int value) Addsaresponseheaderwiththegivennameandintegervalue. booleancontainsHeader(java.lang.String name) Returnsabooleanindicatingwhetherthenamedresponseheaderhasalreadybeenset. java.lang.StringencodeRedirectUrl(java.lang.String url) Deprecated. Asofversion2.1,useencodeRedirectURL(Stringurl)instead java.lang.StringencodeRedirectURL(java.lang.String url) EncodesthespecifiedURLforuseinthesendRedirectmethodor,ifencodingisnotneeded,returnstheURLunchanged. java.lang.StringencodeUrl(java.lang.String url) Deprecated. Asofversion2.1,useencodeURL(Stringurl)instead java.lang.StringencodeURL(java.lang.String url) EncodesthespecifiedURLbyincludingthesessionIDinit,or,ifencodingisnotneeded,returnstheURLunchanged. voidsendError(int sc) Sendsanerrorresponsetotheclientusingthespecifiedstatuscodeandclearingthebuffer. voidsendError(int sc,java.lang.String msg) Sendsanerrorresponsetotheclientusingthespecifiedstatusclearingthebuffer. voidsendRedirect(java.lang.String location) SendsatemporaryredirectresponsetotheclientusingthespecifiedredirectlocationURL. voidsetDateHeader(java.lang.String name,long date) Setsaresponseheaderwiththegivennameanddate-value. voidsetHeader(java.lang.String name,java.lang.String value) Setsaresponseheaderwiththegivennameandvalue. voidsetIntHeader(java.lang.String name,int value) Setsaresponseheaderwiththegivennameandintegervalue. voidsetStatus(int sc) Setsthestatuscodeforthisresponse. voidsetStatus(int sc,java.lang.String sm) Deprecated. Asofversion2.1,duetoambiguousmeaningofthemessageparameter.TosetastatuscodeusesetStatus(int),tosendanerrorwithadescriptionusesendError(int,String).Setsthestatuscodeandmessageforthisresponse.Methodsinheritedfrominterfacejavax.servlet.ServletResponseflushBuffer,getBufferSize,getCharacterEncoding,getLocale,getOutputStream,getWriter,isCommitted,reset,resetBuffer,setBufferSize,setContentLength,setContentType,setLocaleHttpSessionpublicabstractinterfaceHttpSessionProvidesawaytoidentifyauseracrossmorethanonepagerequestorvisittoaWebsiteandtostoreinformationaboutthatuser.TheservletcontainerusesthisinterfacetocreateasessionbetweenanHTTPclientandanHTTPserver.Thesessionpersistsforaspecifiedtimeperiod,acrossmorethanoneconnectionorpagerequestfromtheuser.Asessionusuallycorrespondstooneuser,whomayvisitasitemanytimes.TheservercanmaintainasessioninmanywayssuchasusingcookiesorrewritingURLs.MethodSummary java.lang.ObjectgetAttribute(java.lang.String name) Returnstheobjectboundwiththespecifiednameinthissession,ornullifnoobjectisboundunderthename. java.util.EnumerationgetAttributeNames() ReturnsanEnumerationofStringobjectscontainingthenamesofalltheobjectsboundtothissession. longgetCreationTime() Returnsthetimewhenthissessionwascreated,measuredinmilliseconds sincemidnightJanuary1,1970GMT. java.lang.StringgetId() Returnsastringcontainingtheuniqueidentifierassignedtothissession. longgetLastAccessedTime() Returnsthelasttimetheclientsentarequestassociatedwiththissession,asthenumberofmillisecondssincemidnightJanuary1,1970GMT,andmarkedbythetimethecontainerrecievedtherequest. intgetMaxInactiveInterval() Returnsthemaximumtimeinterval,inseconds,thattheservletcontainerwillkeepthissessionopenbetweenclientaccesses. ServletContextgetServletContext() ReturnstheServletContexttowhichthissessionbelongs. HttpSessionContextgetSessionContext() Deprecated. AsofVersion2.1,thismethodisdeprecatedandhasnoreplacement.ItwillberemovedinafutureversionoftheJavaServletAPI. java.lang.ObjectgetValue(java.lang.String name) Deprecated. AsofVersion2.2,thismethodisreplacedbygetAttribute(java.lang.String). java.lang.String[]getValueNames() Deprecated. AsofVersion2.2,thismethodisreplacedbygetAttributeNames() voidinvalidate() Invalidatesthissessionthenunbindsanyobjectsboundtoit. booleanisNew() Returnstrueiftheclientdoesnotyetknowaboutthesessionoriftheclientchoosesnottojointhesession. voidputValue(java.lang.String name,java.lang.Object value) Deprecated. AsofVersion2.2,thismethodisreplacedby setAttribute(java.lang.String,java.lang.Object) voidremoveAttribute(java.lang.String name) Removestheobjectboundwiththespecifiednamefromthissession. voidremoveValue(java.lang.String name) Deprecated. AsofVersion2.2,thismethodisreplacedbyremoveAttribute(java.lang.String) voidsetAttribute(java.lang.String name,java.lang.Object value) Bindsanobjecttothissession,usingthenamespecified. voidsetMaxInactiveInterval(int interval) Specifiesthetime,inseconds,betweenclientrequestsbeforetheservletcontainerwillinvalidatethissession.ServletContextpublicabstractinterfaceServletContextDefinesasetofmethodsthataservletusestocommunicatewithitsservletcontainer,forexample,togettheMIMEtypeofafile,dispatchrequests,orwritetoalogfile.MethodSummary java.lang.ObjectgetAttribute(java.lang.String name) Returnstheservletcontainerattributewiththegivenname,ornullifthereisnoattributebythatname. java.util.EnumerationgetAttributeNames() ReturnsanEnumerationcontainingtheattributenamesavailablewithinthisservletcontext. ServletContextgetContext(java.lang.String uripath) ReturnsaServletContextobjectthatcorrespondstoaspecifiedURLontheserver. java.lang.StringgetInitParameter(java.lang.String name) ReturnsaStringcontaining thevalueofthenamedcontext-wideinitializationparameter,ornulliftheparameterdoesnotexist. java.util.EnumerationgetInitParameterNames() Returnsthenamesofthecontext'sinitializationparametersasanEnumerationofStringobjects,oranemptyEnumerationifthecontexthasnoinitializationparameters. intgetMajorVersion() ReturnsthemajorversionoftheJavaServletAPIthatthisservletcontainersupports. java.lang.StringgetMimeType(java.lang.String file) ReturnstheMIMEtypeofthespecifiedfile,ornulliftheMIMEtypeisnotknown. intgetMinorVersion() ReturnstheminorversionoftheServletAPIthatthisservletcontainersupports. RequestDispatchergetNamedDispatcher(java.lang.String name) ReturnsaRequestDispatcherobjectthatactsasawrapperforthenamedservlet. java.lang.StringgetRealPath(java.lang.String path) ReturnsaStringcontainingtherealpathforagivenvirtualpath. RequestDispatchergetRequestDispatcher(java.lang.String path) ReturnsaRequestDispatcherobjectthatactsasawrapperfortheresourcelocatedatthegivenpath. java.net.URLgetResource(java.lang.String path) ReturnsaURLtotheresourcethatismappedtoaspecifiedpath. java.io.InputStreamgetResourceAsStream(java.lang.String path) ReturnstheresourcelocatedatthenamedpathasanInputStreamobject. java.util.SetgetResourcePaths(java.lang.String path) Returnsadirectory-likelistingofallthepathstoresourceswithinthe webapplicationwhoselongestsub-pathmatchesthesuppliedpathargument. java.lang.StringgetServerInfo() Returnsthenameandversionoftheservletcontaineronwhichtheservletisrunning. ServletgetServlet(java.lang.String name) Deprecated. AsofJavaServletAPI2.1,withnodirectreplacement.ThismethodwasoriginallydefinedtoretrieveaservletfromaServletContext.Inthisversion,thismethodalwaysreturnsnullandremainsonlytopreservebinarycompatibility.ThismethodwillbepermanentlyremovedinafutureversionoftheJavaServletAPI.Inlieuofthismethod,servletscanshareinformationusingtheServletContextclassandcanperformsharedbusinesslogicbyinvokingmethodsoncommonnon-servletclasses. java.lang.StringgetServletContextName() ReturnsthenameofthiswebapplicationcorrepondingtothisServletContextasspecifiedinthedeploymentdescriptorforthiswebapplicationbythedisplay-nameelement. java.util.EnumerationgetServletNames() Deprecated. AsofJavaServletAPI2.1,withnoreplacement.ThismethodwasoriginallydefinedtoreturnanEnumerationofalltheservletnamesknowntothiscontext.Inthisversion,thismethodalwaysreturnsanemptyEnumerationandremainsonlytopreservebinarycompatibility.ThismethodwillbepermanentlyremovedinafutureversionoftheJavaServletAPI. java.util.EnumerationgetServlets() Deprecated. AsofJavaServletAPI2.0,withnoreplacement.ThismethodwasoriginallydefinedtoreturnanEnumerationofalltheservletsknowntothisservletcontext.Inthisversion,thismethod alwaysreturnsanemptyenumerationandremainsonlytopreservebinarycompatibility.ThismethodwillbepermanentlyremovedinafutureversionoftheJavaServletAPI. voidlog(java.lang.Exception exception,java.lang.String msg) Deprecated. AsofJavaServletAPI2.1,uselog(Stringmessage,Throwablethrowable)instead.Thismethodwasoriginallydefinedtowriteanexception'sstacktraceandanexplanatoryerrormessagetotheservletlogfile. voidlog(java.lang.String msg) Writesthespecifiedmessagetoaservletlogfile,usuallyaneventlog. voidlog(java.lang.String message,java.lang.Throwable throwable) WritesanexplanatorymessageandastacktraceforagivenThrowableexceptiontotheservletlogfile. voidremoveAttribute(java.lang.String name) Removestheattributewiththegivennamefromtheservletcontext. voidsetAttribute(java.lang.String name,java.lang.Object object) Bindsanobjecttoagivenattributenameinthisservletcontext.