JavaWeb开发知识总结(Cookie,Session)

1. 会话技术

会话可简单理解为:用户开一个浏览器访问网站,访问服务器的多个web资源,然后关闭浏览器,这整个过程称之为一个会话。

2. 会话数据保存的两种技术

由于会话是发生在客户端浏览器和服务器之间,则保存会话数据有两种思路:将会话数据保存在客户端浏览器或者保存在服务器端中。保存在客户端时采用的是Cookie技术,保存在服务器端时使用的是Session技术。

2.1 Cookie技术

Cookie是客户端技术,web服务器端程序把每个访问用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的cookie数据到服务器中,根据cookie中保存的数据web服务器就能处理用户各自的数据。

2.2 Session技术

Session是服务器端技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的session对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务。

3. Cookie技术

3.1 Cookie常用API

cookie数据是以键值对的形式存在的,只不过其键值的数据类型均为字符串类型。

方法

方法类型

说明

Cookie(String name, String value)

构造方法

创建Cookie对象,是创建Cookie对象必须使用的方法

String getName()

成员方法

获取cookie对象的名称

String getValue()

成员方法

获取cookie对象的存储值

void setPath(String uri)

成员方法

设置cookie有效路径,就是指定cookie只在访问服务器指定的路径下有效,在其他的路径是无效的,也可理解为是cookie的作用范围

set MaxAge(intmaxAge)

成员方法

设置cookie的有效时间,参数是秒,参数为0时为销毁cookie,前提是设置的有效路径一致;参数指定 cookie 的最大生存时间(以秒为单位)的整数,如果为负数,则表示不存储该 cookie,如果为0,则表示删除该cookie.cookie默认情况下的有效期是一次会话,当用户关闭浏览器后cookie就消失了,当设置cookie的有效期后,关闭浏览器时会将cookie信息写到用户的本地,在cookie有效期内再打开浏览器再访问该网站时会将之前的cookie数据带到服务器端.

3.2 Cookie的使用:jsp知识键后续章节

cookie技术是客户端技术,当客户端浏览器和服务器进行通信时,客户端的请求数据均会封装到请求中,服务器向客户端输出的数据均在响应中,则在Servlet中封装用户请求数据HttpServletRequest对象中,该对象提供了Cookie[] getCookies()方法获取客户端存储的cookie数据,在响应的HttpServletResponse对象中,封装了void addCookie(Cookie cookie) 方法向客户端存储cookie数据。

Cookie的销毁

Cookie分为会话级别的Cookie和持久化级别的Cookie,这两中Cookie的销毁方式不同:

Cookie类别

销毁时机

会话级别Cookie

客户浏览器关闭后销毁;手动销毁是使用setMaxAge(0)方法,前提是创建Cookie社设置的路径和销毁时创建的Cookie的名称和有效路径一致

持久化级别Cookie(设置Cookie有效时间)

有效时间过期后可以销毁;手动销毁是使用setMaxAge(0)方法,前提是创建Cookie社设置的路径和销毁时创建的Cookie的名称和有效路径一致

注意事项: 当使用手动删除Cookie时,创建Cookie时设置的有效路径和销毁Cookie时设置的有效路径必须一致,否则无法删除Cookie。

Cookie使用案例:记录用户上次访问时间及IP地址
/**
 * 用户访问的Servlet
 * 用户访问时,向用户浏览器显示该用户是第几位访客
 * 如果不是第一次访问,就显示上次访问时间及访问的IP地址
 */
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    public void init() throws ServletException {
        // 初始化全局的变量,记录登陆成功的人数
        this.getServletContext().setAttribute("count", 0);
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 记录登陆成功的人数
        Integer count = (Integer) this.getServletContext().getAttribute("count");
        // 获取浏览器的cookies
        Cookie[] cookies = request.getCookies();
        Cookie findLastVisitCookie = CookieUtils.findCookie(cookies,
                "lastVisit");
        Cookie findLastVisitIPCookie = CookieUtils
                .findCookie(cookies, "ip");
        // 当在客户端传过来的cookie中没有找到指定的cookie时,代表是第一次访问
        if (findLastVisitCookie == null) {
            response.getWriter().println("您是第" + (++count) + "位登陆成功的用户");
        } else {
            // 在cookie数组中找到时,代表不是第一次访问,则显示上次访问的时间
            Long value = Long.parseLong(findLastVisitCookie.getValue());
            Date date = new Date(value);
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            response.getWriter().println("您是第"+ (++count)
                            + "位登陆成功的用户,您上次访问时间"
                            + sdf.format(date)
                            + (findLastVisitIPCookie == null ? "": ("上次访问ip地址:"+findLastVisitIPCookie.getValue())));
        }
        // 将访问的总人数存入ServletContext域中
        this.getServletContext().setAttribute("count", count);
        // 将本次访问的时间及IP地址添加到响应头中
        Cookie visitCookie = new Cookie("lastVisit", ""+ System.currentTimeMillis());
        Cookie visitIPCookie = new Cookie("ip", request.getRemoteAddr());
        response.addCookie(visitCookie);
        response.addCookie(visitIPCookie);
    }
}
/**
 * 查找指定cookie中是否包含指定的cookie信息
 */
public class CookieUtils {
    private CookieUtils(){}
    /**
     * 在指定的cookie数组中查找指定的cookie
     * @param cookies 要查找的cookie数组
     * @param name 要查找的cookie的名称
     * @return 返回查找的cookie
     */
    public static Cookie findCookie(Cookie[] cookies ,String name) {
        // 如果cookie数组为空,则直接返回null
        if(cookies == null) {
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if(name.equals(cookie.getName())) {
                    return cookie;
                }
            }
            return null;
        }
    }
}
Cookie使用案例:删除Cookie
/**
 * 用户访问该Servlet时创建Cookie
 */
public class CreatCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 创建Cookie信息并写到客户端的cookie中
        Cookie cookie = new Cookie("visHistory", "somnus");
        // 设置Cookie的有效路径为项目名路径
        cookie.setPath("/JavaWeb_Cookie");
        // 将Cookie写到客户端
        response.addCookie(cookie);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

/**
 * 用户访问该Servlet时销毁之前的Cookie数据
 */
public class ClearCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 将cookie的有效时间设为0即可,注意需要设置有效路径一致
        // 获取客户端浏览器中的Cookie数据
        Cookie[] cookies = request.getCookies();
        // 查找之前创建的Cookie数据
        Cookie findCookie = CookieUtils.findCookie(cookies, "visHistory");
        if(findCookie != null) {
            // 设置Cookie的有效路径,必须和第一次创建该Cookie时设置有效路径一致
            findCookie.setPath("/JavaWeb_Cookie");
            // 将Cookie的有效时间设为0
            findCookie.setMaxAge(0);
            // 再将Cookie写回到客户端,以销毁客户端的Cookie
            response.addCookie(findCookie);
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

3.3 Cookie使用时注意事项

  1. 一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。
  2. 一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。
  3. 浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
  4. 如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。

4. Session技术

Session技术是将客户端访问的数据保存在服务器端,Session是基于Cookie技术的。当用户访问服务器时,服务器会创建一个session,并创建一个SessionID进行用户的标示,同时将该SessionID以Cookie的方式写回到客户端中。当客户端下次再访问该网页时,会带着该SessionID到服务器端,则服务器端就可以用SessionID来区分用户了。由于SessionID是保存在客户端的Cookie中,则客户端访问服务器的session在关闭浏览器后就Cookie就消失了,则保存在Cookie中sessionID也消失了,但保存在服务器端的sessionID还是存在的,服务器端的session默认的有效期默认是30分钟(在tomcat的web.xml中配置,在项目的web.xml中可以使用<session-config><session-timeout>过期时间</session-timeout></session-config> 进行配置);当用户再次打开浏览器访问服务器时,由于客户端Cookie中没有上次访问时保存的sessionID,则服务器会为用户重新创建一个session。

4.1 Session常用API

Session对象是域对象,可以存储数据。保存的数据是键值对的形式,键是String类型,值是Object类型。其作用范围是一次会话。

方法

方法类型

方法说明

void setAttribute(String name, Object value)

成员方法

将绑定到指定名称的对象存储到session中

Object getAttribute(String name)

成员方法

获取绑定到指定名称的对象数据

void removeAttribute(String name)

成员方法

移除指定名称的数据

4.2 Session的使用:jsp知识键后续章节

用户的请求封装在HttpServletRequest对象中,HttpServletRequest对象中有Session getSession() 方法可以获取session对象。通过Session对象的setAttribute() 方法存储数据,getAttribute() 方法获取数据。Session存储的数据的有效范围是一次会话(可以有多次请求)。 一般用在验证码的校验和保证系统是单用户登陆。

Session使用案例:保证单用户登陆
/** UserServlet.java文件
 * 用户登陆的Servlet
 * 当第一个用户登陆时,将第一个登陆成功的用户保存在session中
 * 当用户再浏览器不关闭的情况下,再开一个网页进行登陆时,
 * 进行判断session中存储的已登录的用户是否存在,如果不存在就允许登陆
 * 如果存在,则通过在登陆页面将保存在session中的错误信取出进行显示
 */
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 从session从取出当前登陆的用户
        User sessionUser = (User) request.getSession().getAttribute("loginUser");
        // 如果session中没有保存的用户,则允许登陆
        if(sessionUser == null) {
            request.setCharacterEncoding("utf-8");
            User user = new User();
            user.setUserName(request.getParameter("username"));
            user.setPassword(request.getParameter("password"));
            UserService userService = new UserService();
            User checkLogin = userService.checkLogin(user);
            // 设置响应的内容是html格式,字符编码是UTF-8,UTF只能大写
            response.setContentType("text/html;charset=UTF-8");
            if(checkLogin != null) {
                // 如果登陆成功就记录当前登陆的用户,并跳转到主页面
                request.getSession().setAttribute("loginUser", checkLogin);
                // index.html可以随意定义
                response.sendRedirect(request.getContextPath()+"/index.html");
            } else {
                // 当用户验证失败时,转到登陆页面进行错误信息提示
                request.getSession().setAttribute("failMsg", "用户名或密码错误!");
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        // 当session中已经存在登陆的用户,则不允许登陆,并显示提示信息
        } else {
            request.getSession().setAttribute("failMsg", "已有用户登陆,您不能登陆");
            // request.getContextPath()代表的是当前项目名路径
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
}
<!--login.jsp部分代码-->
<div class="col-md-5">
  <div>
    <font>会员登录</font>USER LOGIN
    <div>
      <!--jsp代码-->
      <%
         // 从session域中获取错误信息的对象,如果不为null,就进行显示
         String msg = (String)request.getSession().getAttribute("failMsg");
         if(msg != null) {
      %>
      <h4 class="text-danger"><%=msg  %></h4>
      <%
         }
      %>
    </div>
    <form class="form-horizontal"action="/JavaWeb__Session/UserServlet" method="post">
      <div class="form-group">
        <label for="username">用户名</label>
        <div class="col-sm-6">
          <input type="text"  id="username" name="username" placeholder="请输入用户名">
        </div>
      </div>
      <div class="form-group">
        <label for="inputPassword3">密码</label>
        <div class="col-sm-6">
          <input type="password" id="inputPassword3" name="password" placeholder="请输入密码">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <input type="submit" width="100" value="登录" name="submit"border="0">
        </div>
      </div>
    </form>
  </div>
</div>
Session使用案例:验证码的校验

验证码是通过swing组件进行绘制的。在自定义Servlet中定义绘制验证码的功能,然后再登陆页面的验证码的图片src路径设为访问该Servlet的路径,则在每次访问该Servlet时都会返回一个验证码。验证码的校验思想是:将Servlet中每次生成的验证码保存在session域中,客户端登陆时需要提交输入的验证码,在提交到数据的Servlet中获取session域中存储的验证码,然后和用户输入的进行比较即可,根据比较的结果向客户端输出信息。 验证码的刷新,就是重新向验证码生成的Servlet请求,在登陆页面刷新验证码需要使用js进行改变验证码图片的src的路径值即可。

实现步骤:

  1. 加载login.html时会请求验证码的CheckImgServlet,在CheckImgServlet中生成验证码,将生成验证码的随机的4个字母或数字保存到session域中;
  2. 在登陆页面中输入验证码值,点提交,提交到UserServlet中;
  3. 在UserServlet中获得提交的验证码,同时从session中域中获得CheckImgServlet生成的验证码;
  4. 比对两个验证码值是否一致;
  5. 将session中保存的验证码清空.
/**
 * 生成验证码图片的Servlet
 */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckImgServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 禁止缓存
        // response.setHeader("Cache-Control", "no-cache");
        // response.setHeader("Pragma", "no-cache");
        // response.setDateHeader("Expires", -1);
        int width = 120;
        int height = 40;
        // 步骤一 绘制一张内存中图片
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 步骤二 图片绘制背景颜色 ---通过绘图对象
        Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
        // 绘制任何图形之前 都必须指定一个颜色
        graphics.setColor(getRandColor(200, 250));
        graphics.fillRect(0, 0, width, height);
        // 步骤三 绘制边框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);
        // 步骤四 四个随机数字
        Graphics2D graphics2d = (Graphics2D) graphics;
        // 设置输出字体
        graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
        // 字母和数字的验证码
        String words =
         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        // 汉字的验证码
        // String words = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
        Random random = new Random();// 生成随机数
        // 定义存储生成的随机数的对象
        StringBuffer buffer = new StringBuffer();
        // 定义x坐标
        int x = 10;
        for (int i = 0; i < 4; i++) {
            // 随机颜色
            graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            // 旋转 -30 --- 30度
            int jiaodu = random.nextInt(60) - 30;
            // 换算弧度
            double theta = jiaodu * Math.PI / 180;
            // 生成一个随机数字
            int index = random.nextInt(words.length()); // 生成随机数 0 到 length - 1
            // 获得字母数字
            char c = words.charAt(index);
            // 将生成字符加入buffer
            buffer.append(c);
            // 将c 输出到图片
            graphics2d.rotate(theta, x, 20);
            graphics2d.drawString(String.valueOf(c), x, 20);
            graphics2d.rotate(-theta, x, 20);
            x += 30;
        }

        // 将生产的验证码保存在session中
        request.getSession().setAttribute("iconCode", buffer.toString());

        // 步骤五 绘制干扰线
        graphics.setColor(getRandColor(160, 200));
        int x1;
        int x2;
        int y1;
        int y2;
        for (int i = 0; i < 30; i++) {
            x1 = random.nextInt(width);
            x2 = random.nextInt(12);
            y1 = random.nextInt(height);
            y2 = random.nextInt(12);
            graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
        }
        // 将上面图片输出到浏览器 ImageIO
        graphics.dispose();// 释放资源
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    /**
     * 取其某一范围的color
     * @param fc int 范围参数1
     * @param bc int 范围参数2
     * @return Color
     */
    private Color getRandColor(int fc, int bc) {
        // 取其随机颜色
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
/**
 * 验证用户输入验证码的Servlet
 */
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取用户输入的验证码的验证码
        String code = request.getParameter("code");
        // 如果用户的验证码为空则提示
        if(!code.equals("")) {
            // 验证验证码
            // 获取存储在session中的验证码
            String riconCode = (String) request.getSession().getAttribute("iconCode");
            // 清除session中存储的验证码
            request.getSession().removeAttribute("iconCode");

            // 当验证码和生产的验证码不同时,验证码错误
            if(!riconCode.equalsIgnoreCase(code)) {
                request.setAttribute("msg", "对不起,验证码错误,请重新输入");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                // 验证通过后,可以进行验证用户名和密码等操作
                ...
            }
        } else {
            request.setAttribute("msg", "对不起,验证码不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
<!--login.html部分代码-->
<!-- 验证码 图片-->
<script type="text/javascript" src="/JavaWeb_Session/bookmanager/js/jquery-2.1.1.min.js"></script>
<script>
  //验证码的刷新
  $(function() {
      $("#changIconCode").click(function() {
          // 在每次请求验证码的Servlet时,需要将每次的请求uri设为不同,否则浏览器会查找本地缓存,如果每次请求的uri相同,则不会去向Servlet请求,在请求的后面加上一个时间戳的参数即可(参数是没有实际意义的,只是使得每次请求Servlet的uri不同)
          $("#iconCode").attr("src","/JavaWeb_Session/CheckImgServlet?time"+new Date().getTime());
      });
      $("#iconCode").click(function() {
          $("#iconCode").attr("src","/JavaWeb_Session/CheckImgServlet?time"+new Date().getTime());
      });
  });
</script>
<div class="col-sm-3" style="padding-left:0px;">
  <img alt="验证码加载失败" id="iconCode" src="/JavaWeb_Session/CheckImgServlet">
</div>
<div class="col-sm-3 text-center" style="padding-left:0px;margin-top:6px;">
  <span>看不清,<button type="button" id="changIconCode" class="btn btn-link">换一张</button></span>
</div>

注意事项:在每次请求验证码的Servlet时,需要将每次的请求uri设为不同,否则浏览器会查找本地缓存,如果每次请求的uri相同,则不会去向Servlet请求使得验证码不会刷新;解决办法时在请求的后面加上一个时间戳的参数使得每次请求的uri不同即可(参数是没有实际意义的,只是使得每次请求Servlet的uri不同)。

4.3 Session的创建,销毁和作用范围:

Session的创建:服务器端第一次调用getSession()创建session。

Session的销毁: 三种情况销毁session:浏览器关闭后,session是没有销毁的,而是保存在cookie中的sessionID随着cookie的销毁不存在了,但是服务器端的session还是存在的。

  1. session过期. 默认过期时间为30分钟,session的默认有效时间是30分钟;
  2. 非正常关闭服务器直接销毁session,如果正常关闭服务器时,服务器会将session序列化到硬盘,下次启动时自动加载该session;
  3. 手动调用session.invalidate()进行销毁。

作用范围: 一次会话的过程(多次请求)。不管是重定向(多次请求)或者是转发都能获取到session域中存储的数据, 当客户端关闭浏览器后就不存在了(一次会话过程)。