飞道的博客

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

596人阅读  评论(0)

目录

1 Session基本概念

1.1 快速入门

1.2 实现原理分析

1.3 Session使用细节

1.4 Session的特点

2 Session验证码案例


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)

  
  1. @WebServlet("/SessionDemo1")
  2. public class SessionDemo1 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //使用Session共享数据
  5. HttpSession session = request.getSession();
  6. //存储数据
  7. session.setAttribute( "msg", "hello session");
  8. }
  9. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  10. this.doPost(request, response);
  11. }
  12. }
  13. @WebServlet("/SessionDemo2")
  14. public class SessionDemo2 extends HttpServlet {
  15. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. //获取Session
  17. HttpSession session = request.getSession();
  18. //获取数据
  19. Object msg = session.getAttribute( "msg");
  20. System.out.println(msg);
  21. }
  22. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  23. this.doPost(request, response);
  24. }
  25. }

1.2 实现原理分析

Session的实现是依赖于Cookie的:

1.3 Session使用细节

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

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

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

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


  
  1. //希望客户端关闭后session也相同
  2. Cookie cookie = new Cookie( "JSESSIONID", session.getId());
  3. cookie.setMaxAge( 60* 60);
  4. 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代码:


  
  1. @WebServlet("/loginServlet")
  2. public class LoginServlet extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //1、设置编码
  5. request.setCharacterEncoding( "utf-8");
  6. //2、获取参数
  7. String username = request.getParameter( "username");
  8. String password = request.getParameter( "password");
  9. String checkCode = request.getParameter( "checkCode");
  10. //3、先获取生成的验证码
  11. HttpSession session = request.getSession();
  12. String checkCode_session = (String) session.getAttribute( "checkCode_session");
  13. //删除session中存储的验证码
  14. session.removeAttribute( "checkCode_session");
  15. //判断验证码是否正确
  16. if(checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)){ //忽略大小写比较
  17. //判断用户名密码是否正确
  18. if( "zhangsan".equals(username) && "123".equals(password)){ //演示用,实际需要查询数据库
  19. //登录成功
  20. //存储用户信息,重定向
  21. session.setAttribute( "user",username);
  22. response.sendRedirect(request.getContextPath()+ "/success.jsp");
  23. } else{
  24. //存储信息到request
  25. request.setAttribute( "login_error", "用户名或密码错误");
  26. //转发到登录页面
  27. request.getRequestDispatcher( "/login.jsp").forward(request,response);
  28. }
  29. } else{
  30. //验证码不一致
  31. //存储信息到request
  32. request.setAttribute( "cc_error", "验证码错误");
  33. //转发到登录页面
  34. request.getRequestDispatcher( "/login.jsp").forward(request,response);
  35. }
  36. }
  37. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  38. this.doPost(request, response);
  39. }
  40. }

3)login.jsp代码:


  
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Login </title>
  5. <script>
  6. window.onload = function () {
  7. document.getElementById( "img").onclick = function () {
  8. this.src = "/cookie/checkCodeServlet?time="+ new Date().getTime();
  9. }
  10. }
  11. </script>
  12. <style>
  13. div{
  14. color: red;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <form action="/cookie/loginServlet" method="post">
  20. <table>
  21. <tr>
  22. <td>用户名 </td>
  23. <td> <input type="text" name="username"> </td>
  24. </tr>
  25. <tr>
  26. <td>密码 </td>
  27. <td> <input type="password" name="password"> </td>
  28. </tr>
  29. <tr>
  30. <td>验证码 </td>
  31. <td> <input type="text" name="checkCode"> </td>
  32. </tr>
  33. <tr>
  34. <td colspan="2"> <img id="img" src="/cookie/checkCodeServlet"> </td>
  35. </tr>
  36. <tr>
  37. <td>用户名 </td>
  38. <td colspan="2"> <input type="submit" value="登录"> </td>
  39. </tr>
  40. </table>
  41. </form>
  42. <div> <%=request.getAttribute("cc_error") == null ? "":request.getAttribute("cc_error")%> </div>
  43. <div> <%=request.getAttribute("login_error") == null ? "":request.getAttribute("cc_error")%> </div>
  44. </body>
  45. </html>

4)success.jsp代码:


  
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Title </title>
  5. </head>
  6. <body>
  7. <h1>
  8. <%=request.getSession().getAttribute("user")%>,欢迎您
  9. </h1>
  10. </body>
  11. </html>

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

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

若本文对您有些许帮助,轻抬您发财的小手,关注/评论/点赞/收藏,就是对我最大的支持!

祝君升职加薪,鹏程万里!


转载:https://blog.csdn.net/w464960660/article/details/107562369
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场