一、cookie
1、設置cookie,內容為時間
1
2
3
|
Cookie cookie = new Cookie( "LastAccessTime" ,System.currentTimeMillis()+ "" ); cookie.setMaxAge( 1 * 30 * 24 * 3600 ); //設置有效期1個月 cookie.setPath( "/項目名稱" ); //訪問整個項目都帶cookie |
2、獲得cookie信息
1
2
3
4
5
6
7
8
|
Cookie cookies[] = request.getCookies(); for ( int i = 0 ;cookie!= null &&i<cookies.length;i++){ if (cookies[i].getName().equals( "LastAccessTime" )){ long cookieValues = Long.parseLong(cookies[i].getVlues()); //將String轉化為10進制Long型 Date date = new Date(cookieValues); response.getWrite().print(date); } } |
二、session(getSession()——>session30分鐘未使用)
1、設置session
1
2
|
HttpSession session = request.getSession(); session.setAttribute( "name" , "哈哈哈哈" ); |
2、得到session
1
2
3
|
HttpSession session = request.getSession(); //HttpSession session = request.getSession(false);//只獲取不創建 String str = (String)session.getAttribute( "name" ); |
3、session配置,配置時間
1
2
3
|
< seeeion-config > < session-timeout >20</ session-timeout > </ session-config > |
4、session摧毀
1
2
3
|
HttpSession session = request.getSession(); session.invalidate(); //session.removeAttribute("XXX");//移除某個session |
5、使用地址重寫方式獲得session,只有在cookie禁用下會重寫
1
2
3
4
5
6
|
request.getSession(); String url1 = response.encodingURL( "需要重寫的地址1" ); String url2 = response.encodingURL( "需要重寫的地址2" ); PrintWriter out = response.getWriter; out.print( "<a href = '" +url1+ "'>XXXX</a>" ); out.print( "<a href = '" +url2+ "'>YYYY</a>" ); |
三、客戶端表單提交問題
1、防止提交空密碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
< form action = "/項目/xxx" method = "post" onsubmit = "return dosubmit(this)" > 用戶名:< input type = "text" name = "username" >< br /> 密碼:< input type = "password" name = "password" >< br /> < input type = "submit" value = "提交" > </ form > < script > function dosubmit(obj){ if(obj.category.value==''){ alter("請輸入"); return false; } } </ script > |
2、防止重復提交
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
< form action = "/項目/xxx" method = "post" onsubmit = "return dosubmit()" > 用戶名:< input type = "text" name = "username" >< br /> 密碼:< input type = "password" name = "password" >< br /> < input type = "submit" value = "提交" > </ form > < script > function dosubmit(){ var iscommitted = false; if(!iscommitted){ iscommitted = true; return true; }else{ return false; } } </ script > |
總結
以上就是本文關于Servlet會話技術基礎解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/qq_24065713/article/details/76726613