此处的是指客户端(浏览器)和服务端之间的数据传输。例如用户登陆,购物车等
会话管理就是管理浏览器客户端和服务端之间会话过程产生的会话数据
经常使用的会话技术
以前学会了域对象的做用,因此在会话管理的时候也可使用域对象的概念来找到解决方法。
经常使用的解决方法主要有两种:
数据保存在客户端的Cookie技术
数据保存在服务端的Session技术css
Cookie是客户端技术,程序把每一个用户的数据以cookie的形式写给用户各自的浏览器,当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去。这样,web资源处理的就是各自用户本身的数据了
特色是会话数据保存在浏览器客户端html
Cookie类:用于存储会话数据。经常使用方法以下:
1.构造Cookie对象java
Cookie(java.lang.String name, java.lang.String value)web
2.设置cookieapi
void setPath(java.lang.String uri) :设置cookie的有效访问路径
void setMaxAge(int expiry) : 设置cookie的有效时间
void setValue(java.lang.String newValue) :设置cookie的值浏览器
3.发送cookie到浏览器端保存缓存
void response.addCookie(Cookie cookie) : 发送cookie安全
4.服务器端接收cookie服务器
Cookie[] request.getCookies() : 接收cookiecookie
代码示例:
/** * 测试Cookie的方法 */ @WebServlet(name = "CookieDemo") public class CookieDemo extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.建立Cookie对象 Cookie cookie = new Cookie("name","eric"); //2.设置Cookie参数 //2.1.设置Cookie的有效路径 cookie.setPath("/hello");//默认就是web项目的地址 //2.2.设置Cookie的有效时间 cookie.setMaxAge(20);//该cookie只存活20秒,从最后不调该cookie开始计算 cookie.setMaxAge(-1);//该cookie保存在浏览器内存中,关闭浏览器则销毁该cookie cookie.setMaxAge(0);//删除根该cookie同名的cookie //3.把数据发送到浏览器 response.addCookie(cookie); //4.服务端接收来自浏览器的cookie //方法1: // String name = request.getHeader("cookie"); // System.out.println(name); //方法2: Cookie[] cookies = request.getCookies(); //注意:判断null,不然空指针 if(cookies!=null){ //遍历 for(Cookie c:cookies){ String name = c.getName(); String value = c.getValue(); System.out.println(name+"="+value); } }else{ System.out.println("没有接收cookie数据"); } } }
1.服务器建立Cookie对象,把会话数据存储到Cookie对象中
new Cookie("name","value");
2.服务器发送cookie信息到浏览器
response.addCookie(cookie);
实际上是隐藏发送了一个set-cookie名称的响应头
3.浏览器获得服务器发送的cookie,而后保存在浏览器端
4.浏览器在下次访问服务器时,会带着cookie信息
包含在http的请求头里
5.服务器接收到浏览器带来的cookie信息
request.getCookies();
1.void setPath(java.lang.String uri)
:设置Cookie的有效访问路径,有效访问路径指的事Cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器的时就会带着Cookie信息,不然不带Cookie信息,默认是在当时钱web项目的路径下
2.void setMaxAge(int expiry)
:设置Cookie的有效时间
expiry能够是正整数,负整数,和零
正整数:表示Cookie数据保存浏览器的缓存到硬盘中,数值表示保存的时间
负整数:表示Cookie数据保存到浏览器的内存中,浏览器关闭Cookie就丢失了
零:表示删除同名的Cookie数据
3.Cookie数据类型只能保存非中文字符串类型的。能够保存多个Cookie,可是浏览器通常只容许存放300个Cookie,每一个站点最多存放20个Cookie,每一个Cookie的大小限制为4KB。
功能实现逻辑:
将时间保存在Cookie中,每次访问从Cookie里面调用
第一次访问:
1.获取当前时间,显示到浏览器中
2.建立Cookie对象,时间做为cookie值,名为:lastTime
3.把cookie发送到浏览器保存
第N次访问:
1.获取cookie的数据,取出名为lastTime的cookie
2.获得cookie的值(上次访问时间)
3.显示上次访问时间到浏览器中
4.更新名为lastTime的cookie。值设置为当前时间
5.把更新后的cookie发送给浏览器保存
代码实现:
/** * 案例-用户上次访问的时间 */ @WebServlet("/last") public class HistServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //获取当前时间 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String curTime = format.format(new Date()); //取得cookie Cookie[] cookies = request.getCookies(); String lastTime = null; //第n次访问 if(cookies!=null){ for (Cookie cookie : cookies) { if(cookie.getName().equals("lastTime")){ //有lastTime的cookie,已是第n次访问 lastTime = cookie.getValue();//上次访问的时间 //第n次访问 //1.把上次显示时间显示到浏览器 response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime); //2.更新cookie cookie.setValue(curTime); cookie.setMaxAge(1*30*24*60*60); //3.把更新后的cookie发送到浏览器 response.addCookie(cookie); break; } } } /** * 第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie) */ if(cookies==null || lastTime==null){ //1.显示当前时间到浏览器 response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime); //2.建立Cookie对象 Cookie cookie = new Cookie("lastTime",curTime); cookie.setMaxAge(1*30*24*60*60);//保存一个月 //3.把cookie发送到浏览器保存 response.addCookie(cookie); } } }
逻辑图
这个项目的代码较多,按照功能的不一样放在不一样的包里面
公司域名的倒写+项目名字+功能名字
cenyu.hist.entity 存放实体对象
cenyu.hist.dao Data Access Object 数据访问对象,主要存放实体对象的一些方法(CRUD-create,read,update,delete)
cenyu.hist.servlet 存放servlet程序
cenyu.hist.ytil 存放工具类
cenyu.hist.test 存放测试类
等等
写的顺序:实体对象-->DAO类-->Servlet程序
代码:暂无
Session是服务器端技术,利用这个技术,服务器在运行时能够为每个用户的数据建立一个其独享的Session对象,因为Session为用户浏览器独享,因此当用户在访问服务器的web资源时,能够把各自的数据放在各自的Session中,当用户再去访问服务器中的其余的web资源的时候,其余的web资源再从用户各自的Session中取出数据为用户服务
Session的类是HttpSession类:用于保存会话数据
1.建立或获得session对象
HttpSession getSession()
直接建立一个Session对象
HttpSession getSession(boolean create)
接收布尔值,设置为true时,在没有找到匹配Session编号的对象时新建一个Sessionu对象。若是设置false,则当找不到匹配的Session时,返回null,建议不要用
2.设置session对象
void setMaxInactiveInterval(int interval)
: 设置session的有效时间
java.lang.String getId()
: 获得session编号
void invalidate()
: 销毁session对象
Session对象的方法:
1.setMaxInactiveInterval方法默认30分钟自动回收Session对象
2.使用setMaxInactiveInterval方法修改销毁时间
3.在web.xml文件中全局修改Session默认回收时间
<!-- 修改session全局有效时间:分钟 --> <session-config> <session-timeout>1</session-timeout> </session-config>
4.经过invalidate方法,手动销毁Session对象
3.保存会话数据到session对象
void setAttribute(java.lang.String name, java.lang.Object value) : 保存数据
java.lang.Object getAttribute(java.lang.String name) : 获取数据
void removeAttribute(java.lang.String name) : 清除数据
4.如何避免浏览器的JSESSIONID的cookie随着浏览器关闭而丢失的问题:
解决方法是手动发送一个硬盘保护的cookie给浏览器
代码见案例:
/** * 测试Session的方法 */ @WebServlet(name = "SessionServletDemo") public class SessionServletDemo extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.建立Session对象 HttpSession session = request.getSession(); //2.保存会话数据 session.setAttribute("name","eric"); //3.取出会话数据 String name = (String)session.getAttribute("name"); System.out.println(name); //4. //拿到Session的id System.out.println(session.getId()); //修改Session有效时间 session.setMaxInactiveInterval(20); //销毁session if (session!=null){ session.invalidate(); } //手动发送一个硬盘保存的cookie给浏览器 Cookie c = new Cookie("JSESSION", session.getId()); c.setMaxAge(60*60); response.addCookie(c); } }
代码解读:HttpSession session = request.getSession();
伪码分析执行过程
1.第一次访问建立Session对象,给Session对象分配一个惟一的ID,叫JSESSIONID。
new HttpSession();
2.把JSESSIONID做为Cookie的值发送给浏览器保存
Cookie cookie = new Cookie("JSESSIONID", sessionID);
response.addCookie(cookie);
3.第二次访问的时候,浏览器带着JSESSIONID的cookie访问服务器
4.服务器获得JSESSIONID,在服务器的内存中搜索是否存放对应编号的session对象
5.若是找到对应编号的session对象,直接返回该对象
6.若是找不到对应编号session对象,建立新的session对象,继续走1的流程
结论经过JSESSION的cookie值在服务器找session对象
需求:实现用户登陆效果,若是登陆成功显示:欢迎回来,×××。若是失败,显示登陆失败
使用Session区分不一样的用户来实现,整个代码实现分为三块,登陆表单提交以后的处理逻辑,登陆逻辑,登出逻辑:
默认登陆界面。index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登陆页面</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="/day12/LoginServlet" method="post"> 用户名:<input type="text" name="userName"/> <br/> 密码:<input type="text" name="userPwd"/> <br/> <input type="submit" value="登陆"/> </form> </body> </html>
登陆失败页面:fail.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>信息提示页面</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <font color='red' size='3'>亲, 你的用户名或密码输入有误!请从新输入!</font><br/> <a href="/day12/login.html">返回登陆页面</a> </body> </html>
表单提交以后的主处理逻辑:IndexServlet.java
/** * 用户主页的逻辑 * */ public class IndexServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); String html = ""; /** * 接收request域对象的数据 */ /* String loginName = (String)request.getAttribute("loginName"); */ /** * 2、在用户主页,判断session不为空且存在指定的属性才视为登陆成功!才能访问资源。 * 从session域中获取会话数据 */ //1.获得session对象 HttpSession session = request.getSession(false); if(session==null){ //没有登陆成功,跳转到登陆页面 response.sendRedirect(request.getContextPath()+"/login.html"); return; } //2.取出会话数据 String loginName = (String)session.getAttribute("loginName"); if(loginName==null){ //没有登陆成功,跳转到登陆页面 response.sendRedirect(request.getContextPath()+"/login.html"); return; } html = "<html><body>欢迎回来,"+loginName+",<a href='"+request.getContextPath()+"/LogoutServlet'>安全退出</a></body></html>"; writer.write(html); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
登陆处理逻辑:LoginServlet.java
/** * 处理登陆的逻辑 * */ public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //1.接收参数 String userName = request.getParameter("userName"); String userPwd = request.getParameter("userPwd"); //2.判断逻辑 if("eric".equals(userName) && "123456".equals(userPwd)){ //登陆成功 /** * 分析: * context域对象:不合适,可能会覆盖数据。 * request域对象: 不合适,整个网站必须得使用转发技术来跳转页面 * session域对象:合适。 */ /* request.setAttribute("loginName", userName); //request.getRequestDispatcher("/IndexServlet").forward(request, response); response.sendRedirect(request.getContextPath()+"/IndexServlet"); */ /** * 1、登陆成功后,把用户数据保存session对象中 */ //1.建立session对象 HttpSession session = request.getSession(); //2.把数据保存到session域中 session.setAttribute("loginName", userName); //3.跳转到用户主页 response.sendRedirect(request.getContextPath()+"/IndexServlet"); }else{ //登陆失败 //请求重定向 response.sendRedirect(request.getContextPath()+"/fail.html"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
退出处理逻辑:LogoutServlet.java
/** * 退出逻辑 * */ public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 3、安全退出: * 删除掉session对象中指定的loginName属性便可! */ //1.获得session对象 HttpSession session = request.getSession(false); if(session!=null){ //2.删除属性 session.removeAttribute("loginName"); } //2.回来登陆页面 response.sendRedirect(request.getContextPath()+"/login.html"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
暂无