欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpSession

程序员文章站 2022-07-12 18:13:17
...

HttpSession 服务端的技术

服务器会为每一个用户创建一个独立的HttpSession

/**
 * @author lanou
 * HttpSession原理:
 * 当用户第一次访问Servlet时,服务器端会给该用户创建一个独立的Session,并且生成一个SessionID
 * 这个SessionID在响应浏览器的时候,会被装进cookie中,从而被保存到浏览器中
 * 当用户再一次访问Servlet的时候,请求会携带着cookie中的SessionID去访问
 * 服务器会根据这个SessionID去查看是否有对应的 Session对象
 * 有,就拿出来使用;没有,就创建一个Session(相当于用第一次访问)(看病案例)
 * 
 * 域的范围
 * Context域 > Session域 > Request域
 * Session域,只要会话不结束就会存在,但是Session有默认的存活时间 30分钟
 * 
 */
public class Demo01 extends HttpServlet {

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

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取参数
        String username = request.getParameter("username");

        //获取session对象
        HttpSession session = request.getSession();
        //保存数据
        session.setAttribute("username", username);
        System.out.println(session.getId());
    }

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

}
/**
 * 测试获取session域中的数据
 * @author lanou
 *
 */
public class Demo02 extends HttpServlet {

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

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取session域中的数据
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        System.out.println(username);
        System.out.println(session.getId());
        //响应到网页上
        response.getWriter().write(username+" "+session.getId());

    }

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

}

人类与计算机的图灵测试

1.

public class DoLogin extends HttpServlet {

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

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    // 获取到请求过来的参数(表单提交过来的数据)
    String userName = request.getParameter("userName");
    String pwd = request.getParameter("pwd");
    String code = request.getParameter("code");
    // 获取域中的session
    HttpSession session = request.getSession();
    String wcode = (String) session.getAttribute("wcode");
    PrintWriter out = response.getWriter();
    //连接数据库
    if (userName.equals("zhangsan") && pwd.equals("123")) {
        //判断验证码,忽略大小写
        if (!code.equalsIgnoreCase(wcode)) {
            //提示用户 验证码错误
            //把错误信息从doLogin页面传到1.jsp页面上
            //使用request域保存验证码错误的信息
            request.setAttribute("msg", "验证码错误");
            //请求转发
            request.getRequestDispatcher("1.jsp").forward(request, response);

        }
    } else {
        // 登录失败
        // 两秒回登录页面
        response.setHeader("refresh", "2;url="+request.getContextPath()+"/1.jsp");
    }
}

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

}

2.
public class CodeServlert extends HttpServlet {

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

        //使用jar生成验证码
        ValidateCode vCode = new ValidateCode(100, 25, 4, 9);
        //获取生成的验证码字符串
        String code = vCode.getCode();
        //传值方式 1.拼接网址字符串 2.使用域对象
        //使用session来储存验证码
        request.getSession().setAttribute("wcode", code);
        System.out.println(code);
        //写到网页上(通过响应中的字符流 写回网页)
        vCode.write(response.getOutputStream());
    }

    private void fun(HttpServletResponse response) throws IOException {
        int width = 110;
        int height = 25;
        // 在内存中创建一个图像对象
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 创建一个画笔
        Graphics g = img.getGraphics();

        // 给图片添加背景色
        g.setColor(Color.PINK);// 设置一个颜色
        g.fillRect(1, 1, width - 2, height - 2);// 填充颜色

        // 给边框一个色
        g.setColor(Color.RED);
        g.drawRect(0, 0, width - 1, height - 1);// 设置边框的显示坐标

        // 设置文本样式
        g.setColor(Color.BLUE);
        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 15));

        // 给图片添加文本
        Random rand = new Random();
        int position = 20;
        for (int i = 0; i < 4; i++) {
            g.drawString(rand.nextInt(10) + "", position, 20);// 给图片填充文本
            position += 20;
        }

        // 添加9条干扰线
        for (int i = 0; i < 9; i++) {
            g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
        }
        // 将图片对象以流的方式输出的客户端
        ImageIO.write(img, "jpg", response.getOutputStream());
    }

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

}

3.jsp文件

<script type="text/javascript">
    function changeCode() {
        /* 从文档中取出img图片*/
        var img = document.getElementsByTagName("img")[0];
        /* 获取图片的src属性,并赋值
         注意:如果请求的网址完全相同,则浏览器不会帮你刷新
         可以拼接当前的时间,让每次请求的网址都不一样
        */
        img.src = "/java-web-servlet-3.29/codeServlet?time=" + new Date().getTime();
    }
</script>
</head>
<body>
    <%
       //书写java代码
       //获取request域中的数据
       String msg = (String)request.getAttribute("msg");
       if(msg != null){
             out.write(msg);
       }


    %>
    <form action="/java-web-servlet-3.29/doLogin" method="post">
        用户名:<input type="text" name="userName"/><br>
        密码:<input type="password" name="pwd"/><br>
        验证码:<input type="text" name="code"/>
        <img src="/java-web-servlet-3.29/codeServlet" onclick="changeCode()"/>
        <a href="javascript:changeCode()">看不清换一张</a>
        <br>
        <input type="submit" value="登录"/><br>
    </form>
</body>

4.
配置web.xml