会话之session技术_史国旭的个人总结(第七次课)

什么是Session

使用Cookie和附加URL参数都可以将上一次请求的状态信息传递到下一次请求中,但是如果传递的状态信息较多,将极大降低网络传输效率和增大服务器端程序处理的难度。

Session技术是一种将会话状态保存在服务器端的技术 ,它可以比喻成是医院发放给病人的病历卡和医院为每个病人保留的病历档案的结合方式 。

客户端需要接收、记忆和回送 Session的会话标识号,Session可以且通常是借助Cookie来传递会话标识号。

同一用户的不同页面共享数据(Session)

_史国旭

之session

Session的跟踪机制

1.Servlet API规范中定义了一个HttpSession接口,HttpSession接口定义了各种管理和操作会话状态的方法。

2.HttpSession对象是保持会话状态信息的存储结构,一个客户端在WEB服务器端对应一个各自的HttpSession对象。

3.WEB服务器并不会在客户端开始访问它时就创建HttpSession对象,只有客户端访问某个能与客户端开启会话的Servlet程序时,WEB应用程序才会创建一个与该客户端对应的HttpSession对象。

4.WEB服务器为HttpSession对象分配一个独一无二的会话标识号,然后在响应消息中将这个会话标识号传递给客户端。客户端需要记住会话标识号,并在后续的每次访问请求中都把这个会话标识号传送给WEB服务器,WEB服务器端程序依据回传的会话标识号就知道这次请求是哪个客户端发出的,从而选择与之对应的HttpSession对象

技术

    WEB应用程序创建了与某个客户端对应的HttpSession对象后,只要没有超出一个限定的空闲时间段,HttpSession对象就驻留在WEB服务器内存之中,该客户端此后访问任意的Servlet程序时,它们都使用与客户端对应的那个已存在的HttpSession对象。

    HttpSession接口中专门定义了一个setAttribute方法来将对象存储到HttpSession对象中,还定义了一个getAttribute方法来检索存储在HttpSession对象中的对象,存储进HttpSession对象中的对象可以被属于同一个会话的各个请求的处理程序共享。

Session是实现网上商城的购物车的最佳方案,存储在某个客户Session中的一个集合对象就可充当该客户的一个购物车。

Session的超时管理

WEB服务器无法判断当前的客户端浏览器是否还会继续访问,也无法检测客户端浏览器是否关闭,所以,即使客户已经离开或关闭了浏览器,WEB服务器还要保留与之对应的HttpSession对象。

随着时间的推移而不断增加新的访问客户端,WEB服务器内存中将会因此积累起大量的不再被使用的HttpSession对象,并将最终导致服务器内存耗尽。

WEB服务器采用“超时限制”的办法来判断客户端是否还在继续访问,如果某个客户端在一定的时间之内没有发出后续请求,WEB服务器则认为客户端已经停止了活动,结束与该客户端的会话并将与之对应的HttpSession对象变成垃圾。

如果客户端浏览器超时后再次发出访问请求,WEB服务器则认为这是一个新的会话的开始,将为之创建新的HttpSession对象和分配新的会话标识号。

会话的超时间隔可以在web.xml文件中设置,其默认值由Servlet容器定义。

       <session-config>

              <session-timeout>30</session-timeout>

       </session-config>

session实现原理

 会话

IE禁用Cookie后的session处理

解决方案:URL重写

response. encodeRedirectURL(java.lang.String url)

用于对sendRedirect方法后的url地址进行重写。

response. encodeURL(java.lang.String url)

用于对表单action和超链接的url地址进行重写

Session案例

1.实现简单的购物车(将点击了购买链接的书籍放到购物车页面显示出来即可)

 

IndexServletShopping.java
package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hbsi.dao.BookDao;
import com.hbsi.domain.Book;

public class IndexServletShopping extendsHttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();

out.print("本网站有如下商品:
");
BookDao db=new BookDao();
List list=db.getAll();
for(Book book:list){
Stringurl=response.encodeRedirectURL("BookHistory/servlet/BuyServlet?id="+book.getId());
out.print(book.getName()+"购买
");
}
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}


CartDisplayServlet.java
package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Book;

public class CartDisplayServlet extendsHttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

List list = (List)request.getSession().getAttribute("cart");
for(Book book:list){
out.print(book.getName()+"
");
}

}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}



BuyServlet.java

package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hbsi.dao.BookDao;
import com.hbsi.domain.Book;

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();

Stringbookid=request.getParameter("id");
BookDao bd=new BookDao();
Book book=bd.getBook(bookid);

HttpSession session=request.getSession();

Cookie cookie=newCookie("JSESSIONID",session.getId());
cookie.setMaxAge(30*60);
cookie.setPath("/BookHistory");
response.addCookie(cookie);

List list=(List)session.getAttribute("cart");
if(list==null){
list=new ArrayList();
session.setAttribute("cart", list);
}
list.add(book);
Stringurl=response.encodeRedirectURL("/BookHistory/servlet/CartDisplayServlet");
response.sendRedirect(url);


}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}


2.使用Session完成用户登陆 利用Session实现验证码校验

IndexServletShopping.java

package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hbsi.dao.BookDao;
import com.hbsi.domain.Book;
import com.hbsi.domain.User;

public class IndexServletShopping 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();

User user = (User)session.getAttribute("user");

if(user!=null){

out.print("欢迎您:"+user.getUsername()+"");
}

out.print("<ahref='/BookHistory/Login.html'>登陆</a>");
out.print("<ahref='/BookHistory/servlet/LogoutServlet'>注销</a><br><br>");



out.print("本网站有如下商品:<br>");

  BookDaodb = new BookDao();
 List<Book> list = db.getAll();
 for(Book book:list){
  Stringurl =response.encodeURL("/BookHistory/servlet/BuyServlet?id="+book.getId());
 out.print(book.getName()+"<a href='"+url+"'>购买</a><br>");
  }



}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}


CartDisplayServlet.java
package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hbsi.domain.Book;

public class CartDisplayServlet extendsHttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

List<Book> list = (List<Book>)request.getSession().getAttribute("cart");
for(Book book:list){
out.print(book.getName()+"<br>");
}

}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}



BuyServlet.java

package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hbsi.dao.BookDao;
import com.hbsi.domain.Book;

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 bookid = request.getParameter("id");
BookDao bd = new BookDao();
Book book = bd.getBook(bookid);

HttpSession session = request.getSession();

Cookie cookie = newCookie("JSESSIONID",session.getId());
cookie.setMaxAge(30*60);
cookie.setPath("/BookHistory");
response.addCookie(cookie);

List list = (List)session.getAttribute("cart");
if(list==null){
list = new ArrayList();
session.setAttribute("cart",list);
}
list.add(book);
String url =response.encodeRedirectURL("/BookHistory/servlet/CartDisplayServlet");
response.sendRedirect(url);



}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}



LoginServlet.java

package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hbsi.dao.UserDao;
import com.hbsi.domain.User;

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();



String username =request.getParameter("username");
String password =request.getParameter("password");

String checkcode =request.getParameter("checkcode");
System.out.println(checkcode);

String imgcode = (String) request.getSession().getAttribute("imgcode");
System.out.println(imgcode);
if(checkcode!=null && imgcode!=null&& checkcode.equals(imgcode)){
//处理登陆请求

UserDao udao = new UserDao();
User user = udao.find(username, password);

if(user!=null){
request.getSession().setAttribute("user",user);
response.sendRedirect("/BookHistory/servlet/IndexServletShopping");
}
out.print("用户名密码错");
}else{
out.print("验证码错误!!!");
}



}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}



LogoutServlet.java

package com.hbsi.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet{

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

HttpSession session = request.getSession(false);
       if(session==null){
       response.sendRedirect("/BookHistory/servlet/IndexServletShopping");
       return;
        }
       session.removeAttribute("user");
      //session.invalidate();
       response.sendRedirect("/BookHistory/servlet/IndexServletShopping");
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}

package com.hbsi.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Response3 extends HttpServlet {
    
private static final int WIDTH=130;
private static final int HEIGHT=30;

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
//1.创建图片
BufferedImage image = newBufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

//2.得到图片
Graphics g = image.getGraphics();

//3 对图片进行绘制

//a.设置图片的背景色
setBackGround(g);

//b.设置矩形边框
setBorder(g);

//c.添加干扰线
setRandomLine(g);

//g.向图形中写数据
String checkcode = setRandomNum(g);

request.getSession().setAttribute("imgcode",checkcode);

//4.把图片写给浏览器
//response.setHeader("content-type","image/jpeg");
response.setContentType("image/jpeg");

//告诉浏览器不要缓存
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
response.setIntHeader("Expires",-1);

ImageIO.write(image,"JPEG",response.getOutputStream());

}

private String setRandomNum(Graphics g) {
//g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
Random random = new Random();
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";

StringBuffer sb = new StringBuffer();

int x=10;
for(int i=0;i<4;i++){
int rand = random.nextInt(base.length()-1);
String str = base.charAt(rand)+"";

sb.append(str);


g.setColor(newColor(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

int degree = random.nextInt()%30;
((Graphics2D)g).rotate(degree*Math.PI/180, x,20); 
g.drawString(str, x, 20);
((Graphics2D)g).rotate(-degree*Math.PI/180, x,20);
x +=30;
}
return sb.toString();

}

private void setRandomNum1(Graphics g) {
//g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
Random random = new Random();

int x=10;
for(int i=0;i<4;i++){
//产生随机数
String str =String.valueOf(random.nextInt(10));
g.setColor(newColor(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

int degree = random.nextInt()%30;
((Graphics2D)g).rotate(degree*Math.PI/180, x,20); 
g.drawString(str, x, 20);
((Graphics2D)g).rotate(-degree*Math.PI/180, x,20);
x +=30;
}

}

private void setRandomLine(Graphics g) {
g.setColor(Color.green);
Random random = new Random();
for(int i=0;i<5;i++){
int x1 = random.nextInt(WIDTH);
int y1 = random.nextInt(HEIGHT);

int x2 = random.nextInt(WIDTH);
int y2 = random.nextInt(HEIGHT);

g.drawLine(x1, y1, x2, y2);
}

}

private void setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);

}

private void setBackGround(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0,0, WIDTH, HEIGHT);

}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}


 

3.利用session防止表单重复提交

RepeateFormServlet.java

package com.hbsi.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RepeateFormServlet extendsHttpServlet {

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");

try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {

e.printStackTrace();
}
out.print("已经处理你的信息");
System.out.println("已向数据库注册信息。。。");
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}




RepeateForm.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">
<html>
 <head>
   <title>RepeateForm.html</title>

   <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="this is mypage">
   <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    
   <!--<link rel="stylesheet" type="text/css"href="./styles.css">-->
    
   <script type="text/javascript">
    
    variscommitted = false;
   function checkPost(){
       if(!iscommitted){
             //document.getElementById("sub").disabled = true;
             iscommitted = true;
           return true;
       }else{
           // alert("不能重复提交表单!");
           return false;
        }
    
    }
    
   </script>

 </head>
  
 <body>
  <formaction="/BookHistory/servlet/RepeateFormServlet"method="post" onsubmit="return checkPost()">
      用户名:<inputtype="text" name="username"/><br/>
     <input type="submit" value="提交"id="sub"/>
  
 </form>
 </body>
</html>


您的回应...

相关话题

查看全部

也许你感兴趣

换一批

热门标签

更多