JSP session对象以及图片验证码的实现

来源:互联网 发布:人工智能作业答案 编辑:程序博客网 时间:2024/04/30 13:18
1、session对象
session是浏览器和服务器之间访问的一个会话对象;session是一个容器;session用来记录用户访问服务器的一段持续周期;30分钟;session有一个id,每一个访问服务器的用户,都会有一个自己独有的session,该session在这个周期内唯一;
2、session实现的原理是什么?
    session的唯一id会作为Cookie数据返回浏览器,    下一次访问的时候,客户携带该Cookie,服务器    根据Cookie中的id,来确定用户;    session依赖Cookie技术实现;
3、session的常见方法
sesstion.addAttribute("xxx",Object);//保存数据;Object x = session.getAttribute("xxx");//获取数据;session.removeAttribute("xxx");//删除session中的数据session.getId();//获取idsession.isNew()//判断该session是否是新建,第一访问新建;session.setMaxInactiveInerval(60*60*24);//设置session周期long x = session.lastAccessTime();//获得用户上一次访问时间session.createTime();//获得创建时间
4、session的应用

用户提交数据的时候的会提交验证码,服务器端首先通过request获得用户输入验证码,和session中的验证码对对,如果一致,则继续验证。如果不一致,不继续验证;

购物车

sale.jsp
handle.jsp

checkout.jsp

购物车,session是一个容器,可以保存
用于的购物信息,在不同的页面,
在特定时间范围,共享;

5、如何生成一张图片
<%@ page import="java.io.*,java.awt.*,java.awt.image.*,javax.imageio.*" %><%        response.setDateHeader("Expires",0);        response.setHeader("Cache-Control","no-cache");        response.setHeader("Pragma","no-cache");        out.clear();        pageContext.pushBody();        response.setContentType("image/jpeg");        OutputStream  outx = response.getOutputStream();        BufferedImage img = new BufferedImage(60,20,BufferedImage.TYPE_INT_RGB);        Graphics g = img.getGraphics();        g.setColor(Color.gray);        g.fillRect(0,0,60,20);        g.setColor(Color.red);        int a1=(int)(Math.random()*10);        int a2=(int)(Math.random()*10);        int a3=(int)(Math.random()*10);        int a4=(int)(Math.random()*10);        String numStr=a1+""+a2+""+a3+""+a4;        g.drawString(numStr,5,15);        //在图片上输出数字        //保存numStr到Session        session.setAttribute("checkcode",numStr);    //将图片转换成字节数组    ByteArrayOutputStream   bos = new ByteArrayOutputStream();    ImageIO.write(img,"JPEG",bos);    byte[] buf = bos.toByteArray();    outx.write(buf);    outx.close();%>

主界面大概是这样:

        <form action="login.jsp"  method="get">        username:<input type="text" name="name"/><br>        password:<input type="text" name="password"/><Br>        checkcode:<input type="text" name="checkcode"/><img src="image.jsp" width=60  height=20></img><br>    <input type="submit" value = "login" />        </form>
0 0
原创粉丝点击