会话
1 会话:用户打开浏览器,浏览页面,直到关闭浏览器的过程称为一次会话。 2 会话跟踪技术包括: Cookie(客户端技术) 3 Session(服务器端技术)
cookie
服务器负责:
负责写cookie
负责解析浏览器传过来的cookie
浏览器负责: 负责保存cookie 负责将cookie发送给服务器
浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie(新版本的浏览器有所提升),每个Cookie的大小限制为4KB。 Cookie常用方法: Cookie c = new Cookie(“”,“”) 构造方法 c.getName() 获取cookie名 c.getValue() 获取value值 c.setMaxAge(int 秒) 设置存活时间 setPath() 设置有效路径 Cookies[] cookie = request.getCookies(); 获得浏览器带来的cookie response.addCookie(cookie);将cookie带回浏览器
乱码问题解决
编码:URLEncoder.encode(loginName,"utf-8");
解码:URLDecoder.decode("","UTF-8);
案例1 是否是第一次访问:
1 import javax.servlet.ServletException; 2 import javax.servlet.annotation.WebServlet; 3 import javax.servlet.http.Cookie; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 @WebServlet(name = "w1",urlPatterns = "/w1") 10 public class work1 extends HttpServlet { 11 @Override 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 response.setContentType("text/html;charset=UTF-8"); 14 Cookie[] cs = request.getCookies(); 15 PrintWriter out = response.getWriter(); 16 17 boolean flag = false; 18 19 if(cs!=null){ 20 for(Cookie c:cs){ 21 if("visited".equals(c.getName())){ 22 flag = true; 23 break; 24 } 25 } 26 } 27 if (flag){ 28 out.println("欢迎回来"); 29 }else{ 30 out.println("第一次访问"); 31 Cookie cookie = new Cookie("visited", "visit"); 32 cookie.setMaxAge(24*60*60); 33 response.addCookie(cookie); 34 } 35 } 36 @Override 37 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 38 this.doPost(request, response); 39 } 40 }
案例2: 记录客户端上次访问时间:
1 import javax.servlet.ServletException; 2 import javax.servlet.annotation.WebServlet; 3 import javax.servlet.http.Cookie; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 import java.time.LocalDateTime; 10 @WebServlet(name = "w2",urlPatterns = "/w2") 11 public class Work2 extends HttpServlet { 12 @Override 13 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 14 response.setContentType("text/html;charset=UTF-8"); 15 Cookie[] cs = request.getCookies(); 16 PrintWriter out = response.getWriter(); 17 boolean flag = false; 18 Cookie cookie=null; 19 if(cs!=null){ 20 for(Cookie c:cs){ 21 if("visited2".equals(c.getName())){ 22 flag = true; 23 cookie=c; 24 break; 25 } 26 } 27 } 28 if (flag){ 29 out.print("欢迎回来"); 30 out.print("<h1>上次访问时间为:"+cookie.getValue()+"</h1>"); 31 }else{ 32 out.println("第一次访问"); 33 } 34 Cookie cookie1 = new Cookie("visited2", LocalDateTime.now().toString()); 35 cookie.setMaxAge(24*60*60); 36 response.addCookie(cookie1); 37 } 38 @Override 39 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 40 this.doPost(request, response); 41 } 42 }
案例3: 记录客户访问次数:
1 import javax.servlet.ServletException; 2 import javax.servlet.annotation.WebServlet; 3 import javax.servlet.http.Cookie; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 import java.time.LocalDateTime; 10 @WebServlet(name = "w3",urlPatterns = "/w3") 11 public class work3 extends HttpServlet { 12 @Override 13 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 14 response.setContentType("text/html;charset=UTF-8"); 15 Cookie[] cs = request.getCookies(); 16 PrintWriter out = response.getWriter(); 17 18 boolean flag = false; 19 Cookie cookie=null; 20 if(cs!=null){ 21 for(Cookie c:cs){ 22 if("visited3".equals(c.getName())){ 23 flag = true; 24 cookie=c; 25 break; 26 } 27 } 28 } 29 int i = 0; 30 if (flag){ 31 i = Integer.parseInt(cookie.getValue()); 32 out.print("欢迎回来"); 33 out.print("<h1>访问次数为:"+(++i)+"</h1>"); 34 }else{ 35 out.println("第一次访问"); 36 Cookie cookie1 = new Cookie("visited3", 1+""); 37 cookie1.setMaxAge(24*60*60); 38 response.addCookie(cookie1); 39 } 40 cookie = new Cookie("visited3", i+""); 41 response.addCookie(cookie); 42 43 } 44 45 @Override 46 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 47 this.doPost(request, response); 48 } 49 }
案例4: 记录客户端用户名:
1 @WebServlet(name = "username",urlPatterns = "/username") 2 public class login extends HttpServlet { 3 @Override 4 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 String loginName = request.getParameter("loginName"); 6 String password = request.getParameter("pwd"); 7 String remember = request.getParameter("remember"); 8 int num = Integer.parseInt(remember); 9 10 if("123".equals(loginName.trim()) && "123".equals(password.trim())){ 11 //登录成功,记录登录名 12 if(num!=0){ 13 String name = URLEncoder.encode(loginName, "UTF-8");// 编码 14 Cookie c = new Cookie("loginName",name); 15 c.setMaxAge(num*24*60*60); 16 response.addCookie(c); 17 } 18 }else{ 19 response.sendRedirect("loginUsername.jsp"); 20 } 21 } 22 23 @Override 24 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 25 this.doPost(request, response); 26 } 27 }
案例5: 记录用户的浏览记录:(网站的真实案例)
@WebServlet(name = "username",urlPatterns = "/username") public class login extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String loginName = request.getParameter("loginName"); String password = request.getParameter("pwd"); String remember = request.getParameter("remember"); int num = Integer.parseInt(remember); if("123".equals(loginName.trim()) && "123".equals(password.trim())){ //登录成功,记录登录名 if(num!=0){ String name = URLEncoder.encode(loginName, "UTF-8");// 编码 Cookie c = new Cookie("loginName",name); c.setMaxAge(num*24*60*60); response.addCookie(c); } }else{ response.sendRedirect("loginUsername.jsp"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } <%@ page import="com.cc.utils.CookieUtils" %> <%@ page import="java.util.Arrays" %><%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/8/30 Time: 16:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> <a href="ServletView?id=1"><img src="img/1.jpg" />手电筒</a> <a href="ServletView?id=2"><img src="img/2.jpg" />手机</a> <a href="ServletView?id=3"><img src="img/3.jpg" />电视</a> <a href="ServletView?id=4"><img src="img/4.jpg" />冰箱</a> <a href="ServletView?id=5"><img src="img/5.jpg" />手表</a> <a href="ServletView?id=6"><img src="img/6.jpg" />电脑</a> <hr /> <% Cookie[] cs = request.getCookies(); Cookie c = CookieUtils.findCookieByName("product", cs); if(c!=null){ String value = c.getValue(); String[] ss = value.split(","); for(String str:ss){ %> <img src="img/<%=str%>.jpg" width="150" height="100" /> <% } } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <% String id = (String)request.getAttribute("id"); %> <img src="img/<%=id %>.jpg" width="300" height="400" /> <a href="index.jsp">返回首页</a> </body> </html>
session
和cookie的区别 1 Cookie有大小和个数的限制的. Session存在服务器端没有大小和个数的限制. 2 Cookie存到客户端上 信息不安全. Session的数据相对来说安全.
3.Session运行原理也是基于Cookie :利用Cookie回写一个 JSESSIONID
session方法
HttpSession session = request.getSession(); 创建session
HttpSession session = request.getSession(false); 若没有创建,返回null
session.getId(); 获取session的ID;
session.setAttribute("",Object); 写入信息
session.getAttribute(""); 获取信息
session.removeAttribute(""); 移除信息
session的销毁
1.关闭服务器(非正常关闭服务器)
2.session时间到期 session的默认存活时间是30分钟
3.调用session 的 invalidate()方法
典型应用
Web工程HttpSession的最典型应用是,登录时,当登录成功后,把登录用户的对象保存在Session中,保证一次会话该用户的状态。退出登录时,把该用户从Session中清除。
Session和Cookie的区别和联系
1.数据存储的位置不同 Cookie在客户端 Session在服务器端
2.生命周期不同,Cookie(会话Cookie浏览器关闭 持久化Cookie setMaxAge(秒数))Session(默认30分钟,可以修改)
3.cookie只能存放字符串名值对,session可以是任意对象
4.同一个浏览器接受cookie的个数是有上限
案例1 是否是第一次访问:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String str = ""; HttpSession session = request.getSession(false); if(session==null){ str = "第一次访问"; session = request.getSession(); }else{ str = "欢迎回来"; } response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(str); }
案例2 典型应用登录后保存用户信息:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); UserService service = new UserServiceImpl(); response.setContentType("text/html;charset=utf-8"); User user = service.login(username, password); ServletContext sc= this.getServletContext(); if(user!=null){ //传入session HttpSession session = request.getSession(false); session.setAttribute("user",user); response.sendRedirect("welcome.jsp"); }else{ response.sendRedirect("login.jsp"); } }
<%@ page import="com.cc.bean.User" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <title>Insert title here</title> <script> function changeImage(){ document.getElementById('checkImage').src="CheckCodeServlet?aaa="+Math.random(); } </script> </head> <body> <% User user = (User)session.getAttribute("user"); String str = ""; if (user!=null){ str = user.getUsername(); System.out.println(str); } %> <form action="Servlet" method="post"> username:<input type="text" name="username" value="<%=str%>"/><br/> password:<input type="password" name="password" /><br/> 验证码:<input type="text" size="10" /><img src="CheckCodeServlet" id="checkImage" /><a href="javascript:changeImage()">看不清,换一张</a><br/> <input type="submit" value=" login " /> </form> </body> </html>