1.1 会话管理

1.1.1 概念介绍

会话是指一个终端用户与交互系统进行通讯的过程,这种多次Http连接维护用户与同一个用户发出的不同请求之间关联的情况,我们称之为一个会话(session)

1.1.2 Cookie基本使用

  • 存储在客户端的一小段数据,以key-value的形式存在
  • 添加Cookie

    1. //创建Cookie并写入到客户端
    2. Cookie ck = new Cookie("hobby","girl");
    3. //设置 有效期 ck.setMaxAge(300);
    4. //单位秒 //响应的时候,通过响应头写回到客户端
    5. resp.addCookie(ck);
    6. resp.getWriter().println("<h1>ok</h1>");

    有效期为负数:不存储,关闭浏览器就无效了 正数:指定时间后过期 零:删除(立即删除)

  • 读取Cookie

    1. //读取
    2. Cookie Cookie[] cks = req.getCookies();
    3. if (cks!=null){
    4. for (Cookie ck :cks){
    5. System.out.println(ck.getName()+":"+ck.getValue());
    6. }
    7. }

    每次客户端请求会主动携带Cookie

  • 删除Cookie

    1. //删除的原理: 重复发送一个同名的cooke客户端去,同时设置这个cooke过期时间为0
    2. Cookie cookie = new Cookie("hobby","");
    3. cookie.setMaxAge(0);
    4. resp.addCookie(cookie);
    5. resp.getWriter().println("delete ok");

    1.2 域

    1.2.1 request域

  • 所谓的域就是一块存储空间,在Javaweb中本质是类似于一个Map集合

    1.2.2 域的管理

    ```java

  1. setAttribute(String name, Objcet value) 存数据
  2. Object getAttribute(String name) 取数据
  3. removeAttribute( String name ) 移除 ```

    经验:通常这两种跳转的方式的选择:如果跳转前后不需要传递数据,可以重重定向,如果需要可以使用转发

1.2.3 HttpSession域

Servlet中会话管理(跟踪)使用的是HttpSession,其底层是依靠Cookie来实现的,利用Cookie来传递凭证。Session域,服务器为浏览器开辟的独立空间,每个浏览器独立的空间,用于保护用户的一些信息

1.2.4 Session生命周期

  1. 关闭浏览器Session失效
  2. 不关闭浏览器默认30分钟
  3. 调用API 注销

1.2.5 配置时间

  1. <session-config>
  2. <session-timeout>30</session-timeout>
  3. </session-config>

1.2.6 管理HttpSession域的方法

  • 登录成功后把用户信息存数据存到Session中

    1. if(name.equals("admin")&&pwd.equals("123456")) {
    2. //登录成功,跳转到指定页面
    3. //存入Seesion
    4. req.getSession().setAttribute("curr_name",name);
    5. resp.sendRedirect("/books.do");
    6. }else{
    7. //登录失败
    8. resp.sendRedirect("/page/error.html");
    9. }
  • 其他页从Session取数据,如果有则证明登录过,没有则跳转到登录页面

    1. //判断当前用户是否登录 if( req.getSession().getAttribute("curr_name")!=null ){
    2. ...... 其他逻辑...... }else{
    3. resp.sendRedirect("/login.html");//跳转到登录页面
    4. }

    1.2.4 全局作用域

  • 所谓的域即是空间

  • 用户保存数据空间
  • Servlet三大作用域:
    • Request域
    • Session域
    • Application全局作用域
  • 是一个单例模式
  • 使用方法
  1. //获得全局作用域
  2. ServletContext context = req.getServletContext();
  3. //添加
  4. void setAttribute(String key,Object value);
  5. //获得
  6. Object getAttribute(String key);
  7. //删除
  8. void removeAttribute(String key)
  • 其他API
    1. //转发
    2. getRequestDispatcher("转发的url").forward(req,resp);
    3. //获得网站(上下文根路径)
    4. getContextPath() ;
    5. //获得相对路径的本决定路径。【用于上传文件】
    6. context.getRealPath("/相对路径") 获得相对路径的本决定路径。

    1.3 图片验证

    1.3.1 步骤

  1. 引入jar包
    1. easy-captcha-1.6.2-RELEASE.jar
    2.编写生成图片验证的Servlet
    1. package com.qfedu.servlet;
    2. import com.wf.captcha.SpecCaptcha;
    3. import com.wf.captcha.base.Captcha;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.io.IOException;
    10. //这是一个负责响应一个图片验证码的Servelt
    11. //你请求它,它就响应你一个图片验证码
    12. @WebServlet("/pic") public class CaptchaServlet extends HttpServlet {
    13. @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    14. //落地实现,生成图片验证码
    15. SpecCaptcha captcha = new SpecCaptcha(120,40,4);//创建一个验证码
    16. //保存这个验证码到Session空间 谁的Session?当前请求的客户端的Session
    17. req.getSession().setAttribute("code",captcha.text());
    18. captcha.out( resp.getOutputStream() ); //把这个图片响应个浏览器。
    19. }
    20. }

    1.3.2 网上获取图片验证码

    1. <form action="/login.do" method="post">
    2. <input type="text" name="un" placeholder="输入账号"/>
    3. <input type="password" name="pw" placeholder="输入密码"/>
    4. <input type="text" name="code" placeholder="验证码">
    5. <img src="/pic" onclick="javascript:this.src='/pic?t='+Math.random()" >
    6. <input type="submit" value="登录">
    7. </form>

    1.3.3 登录处理Servlet是否正确

    1. @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. req.setCharacterEncoding("utf-8");
    3. resp.setCharacterEncoding("utf-8");
    4. resp.setContentType("text/html;charset=utf-8");
    5. String name =req.getParameter("un");
    6. String pwd= req.getParameter("pw");
    7. //用户输入的 验证码
    8. String code= req.getParameter("code");
    9. //正确的验证码? 从Session中取
    10. String relCode = req.getSession().getAttribute("code").toString();
    11. if( relCode.equalsIgnoreCase(code) ){
    12. System.out.println("正确"); //其他逻辑比如验证账号密码 }else
    13. {
    14. System.out.println("错误");
    15. }
    16. }