一、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