session之验证码案例

session之验证码案例

基本思路

代码

login.html

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8"/>
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title>会员登录</title>
     <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
     <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
     <script src="js/bootstrap.min.js" type="text/javascript"></script>
     <!-- 引入自定义css文件 style.css -->
     <link rel="stylesheet" href="css/style.css" type="text/css"/>
 ​
     <style>
         body {
             margin-top: 20px;
             margin: 0 auto;
         }
 ​
         .carousel-inner .item img {
             width: 100%;
             height: 300px;
         }
 ​
         .container .row div {
             /* position:relative;
             float:left; */
         }
 ​
         font {
             color: #666;
             font-size: 22px;
             font-weight: normal;
             padding-right: 17px;
         }
     </style>
 </head>
 <body>
 <div class="container" style="width:100%;height:460px;background:#FF2C4C url('img/loginbg.jpg') no-repeat;">
     <div class="row">
         <div class="col-md-7">
             <!--<img src="./img/login.jpg" width="500" height="330" alt="会员登录" title="会员登录">-->
         </div>
 ​
         <div class="col-md-5">
             <div style="width:440px;border:1px solid #E7E7E7;padding:20px 0 20px 30px;border-radius:5px;margin-top:60px;background:#fff;">
                 <font>会员登录</font>USER LOGIN
 ​
                 <div>&nbsp;</div>
                 <form class="form-horizontal" action="login" method="post">
 ​
                     <div class="form-group">
                         <label for="username" class="col-sm-2 control-label">用户名</label>
                         <div class="col-sm-6">
                             <!--表单要加上name属性,否则服务器得到不值-->
                             <input type="text" class="form-control" name="username" id="username" placeholder="请输入用户名">
                         </div>
                     </div>
                     <div class="form-group">
                         <label for="password" class="col-sm-2 control-label">密码</label>
                         <div class="col-sm-6">
                             <input type="password" class="form-control" name="password" id="password" placeholder="请输入密码">
                         </div>
                     </div>
                     <div class="form-group">
                         <label for="vcode" class="col-sm-2 control-label">验证码</label>
                         <div class="col-sm-3">
                             <input type="text" class="form-control" name="vcode" id="vcode" placeholder="请输入验证码">
                         </div>
                         <div class="col-sm-3">
                             <!--指定为servlet,鼠标移上去变成手-->
                             <img src="code" style="cursor: pointer" title="看不清换一张" id="picCode"/>
 ​
                             <script type="text/javascript">
                                 //编写图片的点击事件
                                 document.getElementById("picCode").onclick = function () {
                                     //修改图片的src,并且指定一个变化的参数
                                     this.src = "code?n=" + new Date().getTime();
                                 };
                             </script>
                         </div>
 ​
                     </div>
                     <div class="form-group">
                         <div class="col-sm-offset-2 col-sm-10">
                             <div class="checkbox">
                                 <label>
                                     <input type="checkbox"> 自动登录
                                 </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                 <label>
                                     <input type="checkbox"> 记住用户名
                                 </label>
                             </div>
                         </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"
                                    style="background: url('./img/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
     height:35px;width:100px;color:white;">
                         </div>
                     </div>
                 </form>
             </div>
         </div>
     </div>
 </div>
 </body>
 </html>

验证码图片

 package Servlet;
 ​
 import javax.imageio.ImageIO;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.io.IOException;
 import java.util.Random;
 ​
 /**
  * 目标:生成验证码图片
  */
 @WebServlet(urlPatterns = "/code")
 public class VerCodeServlet extends HttpServlet {
 ​
     // 1. 写一个方法随机获取颜色
     public Color randomColor(){
         // r g b 取值范围 0到255
         Random random = new Random();
         return new Color(
                 random.nextInt(256),
                 random.nextInt(256),
                 random.nextInt(256));
     }
 ​
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 ​
         // 2. 创建缓存图片:指定宽width=90,高 height=30
         int width = 90;
         int height = 30;
         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 ​
         // 3. 获取画笔对象
         Graphics g = image.getGraphics();
 ​
         // 4. 设置画笔颜色,并且填充矩形区域
         g.setColor(Color.white);
         g.fillRect(0, 0, width, height);
 ​
         // 创建可变字符串
         StringBuilder sb = new StringBuilder();
 ​
         // 5. 从字符数组中随机得到字符
         char[] arr = { 'A', 'B', 'C', 'D', 'N', 'E', 'W', 'b', 'o', 'y', '1', '2', '3', '4' };
         // 创建随机对象
         Random r = new Random();
         for (int i = 0; i < 4; i++) {
             // 随机产生一个索引值
             int index = r.nextInt(arr.length);
             // 根据索引获得随机字符
             char ch = arr[index]; // abcd
             // 拼接字符
             sb.append(ch);
             // 设置字体,大小为 18
             g.setFont(new Font(Font.DIALOG,Font.BOLD + Font.ITALIC,18));
             // 设置字的颜色随机
             g.setColor(randomColor());
 ​
             // 绘制字符串
             // 7. 将每个字符画到图片上,位置:
             int x = 5 + (i*20);
             int y = 20;
             g.drawString(String.valueOf(ch),x,y);
         }
 ​
         // 将验证码字符串存储会话域中
         HttpSession session = request.getSession();
         session.setAttribute("verCode", sb.toString());
 ​
         // 8. 画10条干扰线,线的位置是随机的,x 范围在 width 之中,y 的范围在 height 之中。
         for (int i = 0; i < 10; i++) {
             // 设置颜色随机
             g.setColor(randomColor());
             int x1 = r.nextInt(width + 1);
             int x2 = r.nextInt(height + 1);
             int y1 = r.nextInt(width + 1);
             int y2 = r.nextInt(height + 1);
             g.drawLine(x1,y1,x2,y2);
         }
 ​
         // 9. 将缓存的图片输出到响应输出流中
         ImageIO.write(image, "png", response.getOutputStream());
     }
 ​
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doPost(request, response);
     }
 }

LoginServlet.java

 package Servlet;
 ​
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.io.IOException;
 ​
 @WebServlet(name = "LoginServlet",urlPatterns = "/login")
 public class LoginServlet extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         // 1. 获取请求参数(用户名,密码,验证码)
         String username = request.getParameter("username");
         String password = request.getParameter("password");
         String vcode = request.getParameter("vcode");
 ​
         // 2. 从会话域中获取验证码
         HttpSession session = request.getSession();
         String verCode = (String) session.getAttribute("verCode");
 ​
         // 3. 判断用户输入的验证码是否正确,正确执行第4步,否则第5步
         if (verCode.equalsIgnoreCase(vcode)){
             // 4. 判断用户名和密码是否正确
             if ("user".equals(username) && "123456".equals(password)){
                 // 4.1 将用户信息存储到会话域中
                 session.setAttribute("username", username);
                 // 4.2 跳转到欢迎页面
                 response.sendRedirect("welcome");
                 return;
             }
         }
         // 5. 回到登录页面
         response.sendRedirect("login.html");
     }
 ​
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
     }
 }
 ​

WelcomeServlet.java

 package Servlet;
 ​
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.io.IOException;
 import java.io.PrintWriter;
 ​
 @WebServlet(name = "WelcomeServlet",urlPatterns = "/welcome")
 public class WelcomeServlet extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         // 设置内容类型和编码
         response.setContentType("text/html;charset=utf-8");
 ​
         //获得字符打印流
         PrintWriter out = response.getWriter();
 ​
         // 从会话域中获取用户名
         HttpSession session = request.getSession();
         String username = (String) session.getAttribute("username");
         out.println("欢迎你," + username +"<br>");
         out.println("<a href='logout'>退出</a>");
 ​
     }
 ​
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
     }
 }
 ​

LogoutServlet.java

 package Servlet;
 ​
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.io.IOException;
 import java.io.PrintWriter;
 ​
 /**
  * 注销页面
  */
 @WebServlet(name = "LogoutServlet",urlPatterns = "/logout")
 public class LogoutServlet extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         // 设置内容类型和编码
         response.setContentType("text/html;charset=utf-8");
         // 获得字符打印流
         PrintWriter out = response.getWriter();
         // 获得会话域对象
         HttpSession session = request.getSession();
         // 立即销毁会话
         session.invalidate();
         out.println("你已经成功退出");
     }
 ​
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doPost(request, response);
     }
 }
 ​