前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaWeb——会话技术之Session快速入门与验证码登录案例实战(Session实现原理、使用细节、快速入门、Session的特点)

JavaWeb——会话技术之Session快速入门与验证码登录案例实战(Session实现原理、使用细节、快速入门、Session的特点)

作者头像
Winter_world
发布2020-09-25 11:01:04
1.2K0
发布2020-09-25 11:01:04
举报

1 Session基本概念

Session是服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中,HttpSession。

1.1 快速入门

1、获取HttpSession对象:

  • HttpSession session = request.getSession();

2、使用HttpSession对象:

  • Object getAttribute(String name)
  • void setAttribute(String name, Object value)
  • void removeAttribute(String name)
代码语言:javascript
复制
@WebServlet("/SessionDemo1")
public class SessionDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用Session共享数据
        HttpSession session = request.getSession();
        //存储数据
        session.setAttribute("msg","hello session");
    }

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

@WebServlet("/SessionDemo2")
public class SessionDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session
        HttpSession session = request.getSession();
        //获取数据
        Object msg = session.getAttribute("msg");
        System.out.println(msg);
    }

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

1.2 实现原理分析

Session的实现是依赖于Cookie的:

1.3 Session使用细节

Session的使用涉及几个细节问题:

1、当客户端关闭后,服务器不关闭,两次获取的session是同一个吗?

默认情况下不是,浏览器关闭前后打印的session:

若希望客户端关闭后session也相同,可以创建Cookie,键为JSESSIONID,设置最大存活时间:

代码语言:javascript
复制
        //希望客户端关闭后session也相同
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);

2、当客户端不关闭,服务器关闭后,两次获取的session是同一个吗?

不是同一个,因为对象创建完成后,服务器关闭后也跟着消失了,这就出现这样一个问题,举个栗子:

我们打开京东选中商品后加入购物车,这个购物车对应的是Map集合,且集合对象是存在Session中的,我们加入购物车后没有及时结算,出去抽了个烟,这中间京东的服务器重启了,Session对象不是一个了,那么我们之前辛苦找的商品就找不到了,造成用户体验极差。

因此,虽然Session不是同一个,但是也一定要确保数据不丢失:

  • session的钝化:服务器关闭之前,将session对象序列化到硬盘上;
  • session的活化:在服务器启动后,将session文件转化为内存中的session对象即可。

以上两步不需要我们自己完成,Tomcat已经帮我们做了,这里需要注意的是IDEA直接使用Tomcat只能钝化session,但不能活化(因为重启服务器时work文件直接被删除了),我们演示时手动启动/关闭Tomcat:

我们把工程下out目录下的文件打包成.war包,放在Tomcat软件的webapps目录下即可,访问对应的资源,我们再正常关闭服务器,会发现Tomcat软件\work\Catalina\localhost\虚拟目录  下出现SESSIONS.ser,再次启动服务器,该文件就被自动删除。

3、session什么时候被销毁?

1)服务器被关闭时;

2)session对象调用invalidate()方法;

3)session默认失效时间30分钟;可以在Tomcat软件的\conf\web.xml中修改:

1.4 Session的特点

【特点】:

  • 1)session用于存储一次会话的多次请求的数据,存在服务器端;
  • 2)session可以存储任意类型,任意大小的数据;

【session与cookie的区别】

  • 1)session存储数据在服务器端,cookie在客户端;
  • 2)session没有数据大小限制,cookie有;
  • 3)session数据安全,cookie相对不安全;

2 Session验证码案例

【需求】:

1)访问带有验证码的登录页面login.jsp;

2)用户输入用户名、密码、验证码:

  • 若用户名和密码有误,则跳转登录页面,提示:用户名或密码错误;
  • 若验证码输入有误,则跳转登录页面,提示:验证码错误;
  • 若全部输入正确,则跳转到主页sucess.jsp,显示:用户名,欢迎您。

【分析】:

【代码实现】:

1)CheckCodeServlet的代码在上一篇博客已贴出,不再赘述;

2)LoginServlet代码:

代码语言:javascript
复制
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、设置编码
        request.setCharacterEncoding("utf-8");
        //2、获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        //3、先获取生成的验证码
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //删除session中存储的验证码
        session.removeAttribute("checkCode_session");
        //判断验证码是否正确
        if(checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)){//忽略大小写比较
            //判断用户名密码是否正确
            if("zhangsan".equals(username) && "123".equals(password)){ //演示用,实际需要查询数据库
                //登录成功
                //存储用户信息,重定向
                session.setAttribute("user",username);
                response.sendRedirect(request.getContextPath()+"/success.jsp");
            }else{
                //存储信息到request
                request.setAttribute("login_error","用户名或密码错误");
                //转发到登录页面
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }else{
            //验证码不一致
            //存储信息到request
            request.setAttribute("cc_error","验证码错误");
            //转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

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

3)login.jsp代码:

代码语言:javascript
复制
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>

    <script>
        window.onload = function () {
            document.getElementById("img").onclick = function () {

                this.src = "/cookie/checkCodeServlet?time="+new Date().getTime();
            }
        }
    </script>
    <style>
        div{
            color: red;
        }
    </style>
</head>
<body>
    <form action="/cookie/loginServlet" method="post">
        <table>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td>验证码</td>
                <td><input type="text" name="checkCode"></td>
            </tr>
            <tr>
                <td colspan="2"><img id="img" src="/cookie/checkCodeServlet"></td>
            </tr>
            <tr>
                <td>用户名</td>
                <td colspan="2"><input type="submit" value="登录"></td>
            </tr>
        </table>
    </form>

    <div><%=request.getAttribute("cc_error") == null ? "":request.getAttribute("cc_error")%></div>
    <div><%=request.getAttribute("login_error") == null ? "":request.getAttribute("cc_error")%></div>

</body>
</html>

4)success.jsp代码:

代码语言:javascript
复制
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>
        <%=request.getSession().getAttribute("user")%>,欢迎您
    </h1>
</body>
</html>

———————————————————————————————————————

本文为博主原创文章,转载请注明出处!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-07-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 Session基本概念
    • 1.1 快速入门
      • 1.2 实现原理分析
        • 1.3 Session使用细节
          • 1.4 Session的特点
          • 2 Session验证码案例
          相关产品与服务
          验证码
          腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档