Persistent State in HTTP Servlets 持久化状态
我们都知道HTTP协议是一个无状态的协议。而客户的每一次请求都是一个独立的REQUEST对象。 如何把客户一组相关的请求连接在一起。 要用到: HttpSession 当然: Session 是基于 COOKIE 或通过URL重写来支持的。 Cookie: a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management 4.Cookie ---> Text -->(在客户端保存,但服务端控制) name value domain path maxAge >0 Cookie保存n秒 =0 Cookie删除 <0 临时保存在内存里(不做文件保存) Cookie c = new Cookie(name,value); res.addCookie(c); Cookie c = req.getCookie(name); Cookie[] cs = req.getCookies(); 初始化参数:initParam a. ServletConfig 1> 放: <servlet> <init-param> <param-name>fileName</parame-name> <param-value>d:/temp/servlet.log</param-value> </init-param> . . . </servlet> 2> 取: String fileName = ServletConfig.getInitParameter("fileName"); b. ServletContext 1> 放: <context-param> <param-name>fileName</param-name> <param-value>d:/temp/servlet.log</param-value> </context-param> 2> 取:String fileName = ServletContext.getInitParameter("fileName"); c. FilterConfig 1> 放:<filter> <init-param> <param-name>fileName</param-name> <param-value>d:/temp/servlet.log</param-value> </init-param> . . . </filter> 2> 取:String fileName = FilterConfig.getInitParameter("fileName"); 请求 Parameter: 1> url?name=value&gender=boy; 2> form 表单数据 name=value 取: String value = request.getParameter(name); --------------------------------------------------------------------------------------- HttpSession: Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. HttpSession session = req.getSession(); = req.getSession(true/false); 7. HttpSession 1.) 原理: 2.) 生命周期: a.)创建: 在没有Session,通过request.getSession(true); b.)销毁: 结束会话 (1). session.invalidate (2). session 超时 <session-config> <session-timeout>30</session-timeout> </session-config> *单位:分钟 * -1 : 不会销毁 3.) 操做: a.)取Session request.getSession(boolean create); true: 如果有Session ,return session,反之 create Session ,return session; false: 如果有Session ,return session,反之 return null; request.getSession() == request.getSession(true); b.)SessionScope ---> Attribute 4.)维护Session:(传递JSESSIONID) a.) cookie name: JSESSIONID value: FD1AE15096586A55986EFA8AA2DD4179 maxAge: -1 b.) URL重写 目的:URL参数传递jsessionid 操作:String =response.encodeURL(tempURL) String =response.encodeRedirectURL(tempURL) 7BE8DEB7D77DA84C9256E974AEAE1B4B http://localhost:8080/servlet/loginSuccess;jsessionid=7BE8DEB7D77DA84C9256E974AEAE1B4B *注意: 维护Session优先选Cookie --------- 针对一个用户 跨请求 时效,会话结束 ===> 针对一个用户,在一个会话内(时间较短),共享数据 ---------------- url? ---> 传参 url# ---> 定位锚点 url;jsessionid ---> 传递JSessionId 1、什么是Cookie技术? 2、什么是Session技术? 3、Session和Cookie的关系什么? 4、对Cookie编程的步骤。 5、对Session编程的步骤。 6、在Servlet中,如何将web应用中的资源保护起来? |
servlet session的学习
最新推荐文章于 2023-06-30 12:01:20 发布