JavaWeb -- 会话, Cookie 和 Session
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("上次访问时间: ");
//get Cookie 获得上次写入的cookie
Cookie[] cookies = request.getCookies(); //从request获得cookie数组
for(int i=0; cookies!=null && i<cookies.length; i++)
{
if( cookies[i].getName().equals("lastAccessTime") )
{
long cookieValue = Long.parseLong(cookies[i].getValue());
Date date = new Date(cookieValue);
out.print(date.toLocaleString());
}
}
//write cookie 写入相应名字的cookie
Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+""); //新建访问时间cookie
cookie.setMaxAge(1*30*24*3600);
cookie.setPath("/WebTest3");
response.addCookie(cookie); //将cookie添加到response,将会返回到浏览器
}
<!-- 10 minutes 10分钟-->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(); //获得Session
String sessionID = session.getId();
Cookie cookie = new Cookie("JSESSIONID", sessionID);
cookie.setPath("/WebTest3");
cookie.setMaxAge(30*60); //设置保存时间,不然关闭浏览器即销毁相应的Cookie
response.addCookie(cookie);
session.setAttribute("name", "bug a TV");
out.print("bug");
//String url1 = response.encodeURL("/WebTest2/Demo4"); //如果浏览器的Cookie功能被关闭,则需要重写URL
//String url2 = response.encodeURL("/WebTest2/Demo5");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
if(session!=null)
{
String product = (String) session.getAttribute("name");
out.print("name = " + product);
}
}
实现自动登录功能:
<body>
Welcome: ${user.username} <br/>
<a href="/WebTest3/1.html">Login</a> <br/>
<a href="/WebTest3/Demo7">Logout</a> <br/> </body>
<form action="/WebTest3/Demo6" method="post">
用户名:<input type="text" name="username"/> <br/>
密码: <input type="password" name="passwd"/><br/>
登录: <input type="submit" name="submit"/> <br/>
自动登录:<input type="checkbox" name="autoLogin" value="true"/> <br/>
</form>
@WebServlet("/Demo6")
public class Demo6 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Demo6() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
//System.out.println("log: " + username + " " + passwd);
ArrayList<User> list = DB.getAll(); //从数据库获取用户信息
for(User user : list)
{
if(user.getUsername().equals(username) && user.getPasswd().equals(passwd)) //用户名密码校验
{
request.getSession().setAttribute("user", user);
response.sendRedirect("/WebTest3/welcome.jsp"); //获得Session
return;
}
}
out.write("Username or passwd Error");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
class DB
{
private static ArrayList list;
static
{
list = new ArrayList<User>();
list.add(new User("kevin", "123456"));
list.add(new User("xiang", "123456"));
}
public DB() {
super();
// TODO Auto-generated constructor stub
}
public static ArrayList getAll()
{
return list;
}
}
public class User implements Serializable
{
private String username;
private String passwd; public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String username, String passwd) {
super();
this.username = username;
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
登录注销Servlet Demo7
public class Demo7 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Demo7() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
if( session==null)
{
response.sendRedirect("/WebTest3/welcome.jsp");
return;
}
session.removeAttribute("user"); //删除Session中的User 注销
response.sendRedirect("/WebTest3/welcome.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
JavaWeb -- 会话, Cookie 和 Session的更多相关文章
- 会话Cookie及session的关系(Cookie & Session)
会话Cookie及session的关系(Cookie & Session) 在通常的使用中,我们只知道session信息是存放在服务器端,而cookie是存放在客户端.但服务器如何使用sess ...
- JavaWeb之Cookie和Session的区别
Cookie和Session的区别 一.cookie机制和session机制的区别 ********************************************************** ...
- java基础学习:JavaWeb之Cookie和Session
一.会话概述 1.1.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话其中不管浏览器发送多少请求,都视为一次会话,直到 ...
- JavaWeb 补充(Cookie&JSP&Session)
1. 会话技术 1. Cookie 2. Session 2. JSP:入门学习 会话技术 1. 会话:一次会话中包含多次请求和响应. * 一次会话:浏览器第一次给服务器资源发 ...
- 【JavaWeb】 Cookie和Session
Session和Cookie出现的原因: 由于Http是无状态的协议,会话之间没有任何关联,也就是上一次会话和下一次会话没有任何关联,因此出现了会话技术Cookie和Session 下面分别从Cook ...
- 会话Cookie与session的关系
在通常的使用中,我们只知道session信息是存放在服务器端,而cookie是存放在客户端.但服务器如何使用session和客户端之间进行通信,以及jsessionId是怎么回事,这并没有一个完整和正 ...
- 【Javaweb】Cookie和Session
会话技术 什么是会话 从浏览器访问服务器开始,到访问服务器结束,浏览器关闭为止的这段时间内容产生的多次请求和响应,合起来叫做浏览器和服务器之间的一次会话 会话管理作用 共享数据用的,并且是在不同请求间 ...
- IT兄弟连 JavaWeb教程 Cookie和Session应用结合使用
一般对于不要求安全的非敏感数据,建议存储在Cookie中! 对于敏感的数据,占用空间较小的,建议存储在Session中! 对于敏感的,较大的数据,存数据库!
- Django 组件-cookie 与 session
会话跟踪技术 1 什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打个电话,你就是客户端,而10 ...
- Django框架07 /cookie和session
Django框架07 /cookie和session 目录 Django框架07 /cookie和session 1. django请求生命周期 2. cookie 3. session 4. 总结 ...
随机推荐
- SendMessage用法
SendMessage(hWnd,wMsg,wParam,lParam) 参数1:hWnd-窗口句柄.窗口可以是任何类型的屏幕对象. 参数2:wMsg-用于区别其他消息的常量值. 参数3:wParam ...
- oracle复合索引的选择和使用
声明:虽然题目是Oracle.但同样适合MySQL InnoDB索引 在大多数情况下.复合索引比单字段索引好 很多系统就是靠新建一些合适的复合索引.使效率大幅度提高 ...
- iOS自动化构建 xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/D...
报这个错误的原因是xcode-select不在默认的路径 1.找到xcode-select的当前路径终端命令行 xcode-select --print-path /Library/Developer ...
- centos6下手工编译vitess
vitess是youtub开源的一款mysql代理,在ubuntu下编译非常方便.可是在centos下且不能訪问google的情况下坑比較多.近期依据其bootstrap.sh脚本手工编译成功.把过程 ...
- appium mac 下 安装及踩坑
Appium Appium是一个开源.跨平台的测试框架,可以用来测试原生及混合的移动端应用.Appium支持IOS.Android及FirefoxOS平台.Appium使用WebDriver的json ...
- sql with 递归查询
用with实现递归查询 1.数据准备 假定有一个表DiGui,有两个字段Id int ParentId int Id ParentId 4 0 5 0 7 0 2 1 8 5 15 5 9 7 14 ...
- 并行编程(2) - sum.msic.Unsafe 二
整理了几个曾经从网上记录sum.msic.Unsafe类的演示样例.供大家參考: package com.fish.unsafe; import java.io.File; import java.i ...
- php_screw加密安装
php_screw的安装与使用 1.下载:http://sourceforge.net/projects/php-screw/files/ php文件通常以文本格式存贮在服务器端, 很容易被别人读到源 ...
- iOS 动画基础总结篇
iOS 动画基础总结篇 动画的大体分类(个人总结可能有误) 分类.png UIView 动画 属性动画 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 ...
- PHP-Manual的学习----【语言参考】----【类型】-----【对象】
Object 对象1.对象初始化要创建一个新的对象 object ,使用 new 语句实例化一个类: class foo{ function do_foo(){ echo &quo ...