一、会话管理概述
1、什么是会话?
好比一次通话。打开浏览器,点击多次链接(发出多次请求和收到多次的响应),关闭浏览器,这个过程就是一次会话。
有功能 可以 文件 新建会话
2、解决的问题是什么?
共享多次请求中产生的数据。比如购物车。
二、客户端技术:Cookie
0、HTTP协议的消息头
请求消息头:Cookie 客户端向服务器端传递信息
响应消息头:Set-Cookie 服务器端向客户端传递信息
1、Cookie详解:
l 属性:
name:Cookie的名称,必要的属性
value:Cookie的取值(不能为中文),必要的属性
-------------------以下为可选属性
path:Cookie的路径
默认值就是写cookie的那个资源的访问路径
比如:http://localhost:8080/day09_00_cookie/servlet/CookieDemo1 path就是/day09_00_cookie/servlet/
注意:
如果一个存在浏览器缓存中的cookie的路径是/day09/servlet/
当访问http://localhost:8080/day09/CookiePathDemo1时,
浏览器根本不带Cookie给服务器。浏览器比对的是cookie的路径和当前访问的资源的路径。
浏览器满足一下条件就会带cookie给服务器:
当前访问的地址的路径.startWith(已存cookie的路径)。
即:如果一个Cookie的路径设置为了当前应用,说明访问该网站的任何资源时浏览器都带该cookie给服务器。(开发中经常做的)
maxAge:Cookie的最大生存时间。默认是在浏览器的内存中。
domain:Cookie的域名(网站)。默认就是写cookie的那个资源所属的网站。
http://localhost:8080/day09_00_cookie/servlet/CookieDemo1域名就是localhost
version:版本号
comment:注释
u 把Cookie写给客户端:
HttpServletResponse.addCookie(Cookie c):实际上就是向客户端发送了一个响应消息头。
注意:客户端只能保存一个网站最多20个Cookie数据,总共最多300个。每个Cookie的大小不能超过4kb。
l 服务器端获取客户端带来的Cookie:
Cookie [] HttpServletRequest.getCookies();
注意:domain+path+name唯一确定一个Cookie。
2、3个案例
a、显示用户最近的访问时间
public class CookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("您上次访问的时间是:<a href='"+request.getContextPath()+"/servlet/ClearTimeServlet'>清除时间</a>");
//获取指定名称的cookie:lastAccessTime=毫秒值
Cookie cs[] = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
if("lastAccessTime".equals(cs[i].getName())){
//找到了
long time = Long.parseLong(cs[i].getValue());
out.write(new Date(time).toLocaleString());
}
}
//把当前的时间写回去
Cookie c = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
c.setMaxAge(Integer.MAX_VALUE);//单位是秒
response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//清除指定的cookie
public class ClearTimeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//如何唯一定位要删除的cookie:domain+path+name
Cookie c = new Cookie("lastAccessTime", "");
c.setMaxAge(0);
response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
演示Cookie的path
public class CookiePathDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//path:/day09/servlet/
Cookie c = new Cookie("demoCookie", "aaa");
c.setPath(request.getContextPath());// 把路径改为 /day09
c.setMaxAge(Integer.MAX_VALUE);
// c.setDomain("itheima.com");//写了白写
response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class CookiePathDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cs[] = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
if("demoCookie".equals(cs[i].getName())){
//找到了
response.getWriter().write(cs[i].getValue());
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
b、记住登录的用户名
public class LoginUIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = "";
String checked = "";
//得到指定的cookie
Cookie cs[] = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
if("loginInfo".equals(cs[i].getName())){
username = cs[i].getValue();
checked="checked='checked'";
break;
}
}
out.write("<form action='"+request.getContextPath()+"/servlet/LoginServlet' method='post'>");
out.write("用户名:<input type='text' name='username' value='"+username+"'/><br/>");
out.write("密码:<input type='password' name='password' value=''/><br/>");
out.write("记住用户名:<input type='checkbox' name='remember' "+checked+"/><br/>");
out.write("<input type='submit' value='登录'/>");
out.write("</form>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //验证用户名和密码是否正确:此处输什么都正确 String username = request.getParameter("username"); String password = request.getParameter("password"); String remember = request.getParameter("remember");//没有选中就是null Cookie c = new Cookie("loginInfo", username); c.setPath(request.getContextPath()); if(remember==null){ //没有选中:删cookie c.setMaxAge(0); }else{ //用户记住用户名:存cookie c.setMaxAge(Integer.MAX_VALUE); } response.addCookie(c); out.write("登录成功"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
c.显示 最近浏览的产品 (图书)
//book类<br>public class Book {
private String id;
private String name;
private String price;
private String author;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price
+ ", author=" + author + ", description=" + description + "]";
}
public Book(String id, String name, String price, String author,
String description) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
this.description = description;
}
public Book(){}
}
//模拟数据
public class BookDB {
//key:书的id value:id对应的书
private static Map<String,Book> books = new HashMap<String,Book>();
static{
books.put("1", new Book("1", "葵花宝典", "10", "nius", "欲练此功,必须很牛"));
books.put("2", new Book("2", "欲女心经", "2", "xuez", "欲练此功,必须清纯"));
books.put("3", new Book("3", "倾城之恋", "20", "liuc", "爱情经典"));
books.put("4", new Book("4", "辟邪剑法", "10", "wangl", "欲练此功,必须很牛"));
books.put("5", new Book("5", "JavaWeb开发", "100", "yif", "经典著作"));
}
public static Map<String,Book> findAllBooks(){
return books;
}
public static Book findById(String bookId){
return books.get(bookId);
}
}
public class ShowAllBooksServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//显示所有的商品,提供查看详细内容的链接
out.write("<h1>本站有以下好书:</h1>");
Map<String, Book> books = BookDB.findAllBooks();
for(Map.Entry<String, Book> me:books.entrySet()){
out.write(me.getValue().getName()+" <a href='"+request.getContextPath()+"/servlet/ShowDetailsServlet?id="+me.getKey()+"' target='_blank'>查看详细</a><br/>");
}
//显示最近的浏览记录:3条 bookHistory=2-1-3
out.write("<hr/>您最近的浏览记录如下:<br/>");
Cookie cs[] = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
if("bookHistory".equals(cs[i].getName())){
String value = cs[i].getValue();// 2-1-3
String ids[] = value.split("\\-");
for(String id:ids){
out.write(BookDB.findById(id).getName()+"<br/>");
}
break;
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//显示商品的详细内容
//组织数据,向客户端写cookie
public class ShowDetailsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//显示商品的详细内容
String id = request.getParameter("id");
Book book = BookDB.findById(id);
out.write(book.toString());
//组织数据,向客户端写cookie 3条 bookHistory=2-1-3
String bookId = makeId(id,request);
Cookie c = new Cookie("bookHistory", bookId);
c.setPath(request.getContextPath());
response.addCookie(c);
}
//组织数据
/*
客户端带来的cookie 当前访问的书的id 应该写回去的新id
cookie为null 1 bookHistory=1
cookie不为null,但没有bookHistory 1 bookHistory=1
bookHistory=1 2 bookHistory=2-1
bookHistory=1-2 3 bookHistory=3-1-2
bookHistory=1-2 2 bookHistory=2-1
bookHistory=1-2-3 4 bookHistory=4-1-2
bookHistory=1-2-3 2 bookHistory=2-1-3
*/
private String makeId(String id, HttpServletRequest request) {
// cookie为null 1 bookHistory=1
Cookie cs[] = request.getCookies();
if(cs==null){
return id;
}
// cookie不为null,但没有bookHistory 1 bookHistory=1
Cookie bookHistoryCookie = null;
for(Cookie c:cs){
if("bookHistory".equals(c.getName())){
bookHistoryCookie = c;
break;
}
}
if(bookHistoryCookie==null){
return id;
}
// bookHistory=1 2 bookHistory=2-1
// bookHistory=1-2 3 bookHistory=3-1-2
// bookHistory=1-2 2 bookHistory=2-1
String value = bookHistoryCookie.getValue();
String ids[] = value.split("\\-");
LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids));
if(list.size()<3){
if(list.contains(id)){
list.remove(id);
}
}else{
// bookHistory=1-2-3 4 bookHistory=4-1-2
// bookHistory=1-2-3 2 bookHistory=2-1-3
if(list.contains(id)){
list.remove(id);
}else{
list.removeLast();
}
}
list.addFirst(id);
StringBuffer sb = new StringBuffer();
for(int i=0;i<list.size();i++){
if(i>0){
sb.append("-");
}
sb.append(list.get(i));
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
三、服务器端技术:HttpSession
1、HttpSession是一个域对象及HttpSession的原理
void setAttribute(String name,Object value);
Object getAttribute(String name);
void removeAttribute(String name);
String getId()
HttpSession request.getSession();
//演示HttpSession的原理
public class SessionDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
if(name==null){
out.write("请这样访问:http://192.168.33.172:8080/day09_01_HttpSession/servlet/SessionDemo1?name=abc");
return;
}
//得到HttpSession的实例
HttpSession session = request.getSession();
//在创建HttpSession对象的同时,服务器给这个对象分配一个唯一的ID(GUID)
System.out.println("SessionDemo1中HttpSession对象的id:"+session.getId());
session.setAttribute("p", name);
out.write("放了。<a href='http://192.168.33.172:8080/day09_01_HttpSession/servlet/SessionDemo2'>去看看</a>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class SessionDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
System.out.println("SessionDemo2中HttpSession对象的id:"+session.getId());
String v = (String)session.getAttribute("p");
response.getWriter().write(v);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
HttpSession request.getSession(boolean b):
b如果为true,和getSession()完全一样的
b为false,服务器只是查找,找不到不会创建新的,返回null。
HttpSession.invalidate();使HttpSession对象立即失效。
2、3个案例
a、使用Session完成简单的购物功能
使用上边的 book类 和 模拟 bookdb 数据
public class Book implements Serializable
//显示所有可购买的商品,提供购买链接
//提供一个查看购物车的链接
public class ShowAllBooksServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession(); //为了使 url 重写
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//显示所有可购买的商品,提供购买链接
out.write("<h1>本站有以下好书:</h1>");
Map<String, Book> books = BookDB.findAllBooks();
for(Map.Entry<String, Book> me:books.entrySet()){
String url = request.getContextPath()+"/servlet/BuyServlet?id="+me.getKey();
url = response.encodeURL(url);
out.write(me.getValue().getName()+" <a href='"+url+"'>购买</a><br/>");
}
//提供一个查看购物车的链接
String url = request.getContextPath()+"/servlet/ShowCartServlet";
url = response.encodeURL(url);
out.write("<a href='"+url+"'>查看购物车</a>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//把书籍放入购物车
public class BuyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
Book b = BookDB.findById(id);
//放到HttpSession中》用List来存
HttpSession session = request.getSession();
List<Book> cart = (List<Book>) session.getAttribute("cart");
if(cart==null){
cart = new ArrayList<Book>();
session.setAttribute("cart", cart);
}
//肯定有购物车
cart.add(b);
String url = request.getContextPath()+"/servlet/ShowAllBooksServlet";
url = response.encodeURL(url);
out.write(b.getName()+"已放入您的购物车<a href='"+url+"'>继续购物</a>");
//为学习原理而做
// Cookie c = new Cookie("JSESSIONID", session.getId());
// c.setPath(request.getContextPath());
// c.setMaxAge(Integer.MAX_VALUE);
// response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//显示购物车
public class ShowCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
List<Book> cart = (List<Book>)session.getAttribute("cart");
if(cart==null||cart.size()==0){
out.write("您还没有购买任何商品");
return;
}
out.write("<h1>你购买的商品如下</h1>");
for(Book b:cart){
out.write(b.getName()+"<br/>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
b、完成用户的登录
//user类
public class User {
private String username;
private String password;
private String nickname;
public User(){}
public User(String username, String password, String nickname) {
super();
this.username = username;
this.password = password;
this.nickname = nickname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
public class UserDB {
private static List<User> users = new ArrayList<User>();
static{
users.add(new User("wzt", "123", "动感超油"));
}
public static User login(String username,String password){
for(User u:users){
if(u.getUsername().equals(username)&&u.getPassword().equals(password)){
return u;
}
}
return null;
}
}
//模拟主页
public class IndexServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("这是主页");
HttpSession s = request.getSession();
User user = (User)s.getAttribute("user");//获取登录标记
if(user==null){
//说明没有登录
out.write("<a href='"+request.getContextPath()+"/servlet/LoginUIServlet'>登录</a>");
}else{
out.write("欢迎您:"+user.getNickname()+"<a href='"+request.getContextPath()+"/servlet/LogoutServlet'>注销</a>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//提供登录界面
public class LoginUIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("<form action='"+request.getContextPath()+"/servlet/LoginServlet' method='post'>");
out.write("用户名: <input type='text' name='username' /><br/>");
out.write("密码: <input type='password' name='password' /><br/>");
out.write("验证码: <input type='text' name='code' /><img src='"+request.getContextPath()+"/servlet/ImageServlet'/><br/>");
out.write(" <input type='submit' value='登录' /><br/>");
out.write("</form>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//登录检
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = UserDB.login(username, password);
if(user==null){
out.write("错误的用户或密码,2秒后转向登录界面");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/LoginUIServlet");
return;
}
HttpSession session = request.getSession();
//验证码是否正确
String code = request.getParameter("code");
String scode = (String) session.getAttribute("code");
if(!code.equals(scode)){
out.write("错误的验证码,2秒后转向登录界面");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/LoginUIServlet");
return;
}
//登录成功
session.setAttribute("user", user);
out.write("登录成功,2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/IndexServlet");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//注销
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
// session.invalidate();//立即失效
session.removeAttribute("user");
out.write("注销成功,2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/IndexServlet");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width = 120;
int height = 25;
//创建一副内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//得到画笔
Graphics g = image.getGraphics();
//开始画
//边线
g.setColor(Color.BLUE);
g.drawRect(0, 0, width, height);
//填充背景色
g.setColor(Color.YELLOW);
g.fillRect(1, 1, width-2, height-2);
//话干扰线
g.setColor(Color.GRAY);
Random r = new Random();
for(int i=0;i<9;i++)
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
//验证码
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.ITALIC|Font.BOLD, 19));
// String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
int x = 20;
StringBuffer sb = new StringBuffer();
for(int i=0;i<4;i++){
String num = r.nextInt(10)+"";
sb.append(num);
g.drawString(num, x,20 );
// g.drawString(base.charAt(r.nextInt(base.length()))+"", x, 20);
x+=18;
}
request.getSession().setAttribute("code", sb.toString());
//输出
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
ImageIO.write(image, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
c、防止表单的重复提交
//注册页面
public class RegistUIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//产生一个唯一的ID(GUID就是UUID)
// String token = UUID.randomUUID().toString();
String token = new BigInteger(165, new Random()).toString(36).toUpperCase();//GUID
request.getSession().setAttribute("token", token);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("<form action='/day09_01_HttpSession/servlet/RegistServlet' method='post'>");
out.write("姓名:<input name='name'/><br/>");
out.write("<input type='hidden' name='token' value='"+token+"'/><br/>");
out.write("<input type='submit' value='保存'/></form>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class RegistServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }//模拟网络慢
String stoken = (String) request.getSession().getAttribute("token");
String ftoken = request.getParameter("token");
if(ftoken.equals(stoken)){
System.out.println(name);
request.getSession().removeAttribute("token");
}else{
out.write("请不要重复提交");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3、客户端禁用Cookie后的会话数据的保持
客户端永远不会向服务器端带任何cookie。
解决办法:
方式一:(乌龙)文字提示:请不要禁用您的Cookie
方式二:在访问的地址后面加上JSESSIONID=session的id。
http://localhost:8080/servlet/ServletDemo1 URL重写,必须对网站的所有地址都重写
http://localhost:8080/servlet/ServletDemo1;JSESSIONID=123
response.encodeUrl(String url);自动重写。 对购物车案例 修改了
4、HttpSession对象的状态
很多 银行的保护性就是将session 减短了。
public class Book implements Serializable 序列化
总结:
一、会话概述
1、如同一次电话通话。
2、会话中要解决的问题:多次请求中的数据的保持问题。典型:购物车
二、Cookie
1、属性:
name value path maxAge domain version 等
2、HttpServletResponse.addCookie(Cookie c)
3、HttpServletRequest.getCookies()
4、记住用户名和记住用户的浏览记录
三、HttpSession
1、HttpSession是一个域对象
2、HttpSession的原理(借助Cookie)
3、HttpSession.getSession():先查(按照session对象的ID去查),没有再创建。
4、案例:
简单购物车
用户登录和验证码验证
防止表单的重复提交:从原理上明白
5、客户端禁用了Cookie后的会话数据保持问题
URL重写
6、HttpSession对象的状态变化:钝化和激活。 向HttpSession中存放的对象的类,要实现java.io.Serializable接口
7、浏览器何时会开启一次新的会话。