zoukankan      html  css  js  c++  java
  • Session实现验证码登陆笔记

    1.生成验证码Servlet

     1 package com.isit.servlet;
     2 
     3 import javax.imageio.ImageIO;
     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 javax.servlet.http.HttpSession;
    10 import java.awt.*;
    11 import java.awt.image.BufferedImage;
    12 import java.io.IOException;
    13 import java.util.Random;
    14 
    15 @WebServlet("/checkCodeServlet")
    16 public class CheckCodeServlet extends HttpServlet {
    17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    18 
    19 
    20         int width = 100;
    21         int height = 50;
    22 
    23         //1.创建一对象,在内存中图片(验证码图片对象)
    24         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    25 
    26 
    27         //2.美化图片
    28         //2.1 填充背景色
    29         Graphics g = image.getGraphics();//画笔对象
    30         g.setColor(Color.PINK);//设置画笔颜色
    31         g.fillRect(0, 0, width, height);
    32 
    33         //2.2画边框
    34         g.setColor(Color.BLUE);
    35         g.drawRect(0, 0, width - 1, height - 1);
    36 
    37         String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
    38         //生成随机角标
    39         StringBuffer sb = new StringBuffer();
    40         Random ran = new Random();
    41         for (int i = 1; i <= 4; i++) {
    42             int index = ran.nextInt(str.length());
    43             //获取字符
    44             char ch = str.charAt(index);//随机字符
    45             sb.append(ch);
    46             //2.3写验证码
    47             g.drawString(ch + "", width / 5 * i, height / 2);
    48         }
    49         String checkCode = sb.toString();
    50         HttpSession session = request.getSession();
    51         session.setAttribute("checkCode", checkCode);
    52         //2.4画干扰线
    53         g.setColor(Color.GREEN);
    54 
    55         //随机生成坐标点
    56 
    57         for (int i = 0; i < 10; i++) {
    58             int x1 = ran.nextInt(width);
    59             int x2 = ran.nextInt(width);
    60 
    61             int y1 = ran.nextInt(height);
    62             int y2 = ran.nextInt(height);
    63             g.drawLine(x1, y1, x2, y2);
    64         }
    65 
    66 
    67         //3.将图片输出到页面展示
    68         ImageIO.write(image, "jpg", response.getOutputStream());
    69 
    70 
    71     }
    72 
    73     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    74         this.doPost(request, response);
    75     }
    76 }
    CheckCodeServlet

    2.登陆Servlet

     1 package com.isit.servlet;
     2 
     3 import com.isit.dao.UserDao;
     4 import com.isit.entity.User;
     5 import org.apache.commons.beanutils.BeanUtils;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.annotation.WebServlet;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 import javax.servlet.http.HttpSession;
    13 import java.io.IOException;
    14 import java.lang.reflect.InvocationTargetException;
    15 import java.util.Map;
    16 
    17 /**
    18  * @program: LoginServlet
    19  * @description: 登陆
    20  * @author: wxh
    21  * @date: 2019-06-11 15:03
    22  **/
    23 @WebServlet("/loginServlet")
    24 public class LoginServlet extends HttpServlet {
    25     @Override
    26     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    27         this.doPost(req, resp);
    28     }
    29 
    30     @Override
    31     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    32         req.setCharacterEncoding("utf-8");
    33         //1.验证验证码是否正确
    34         HttpSession session = req.getSession();
    35         String checkCode = (String) session.getAttribute("checkCode");
    36         //1.1.验证码错误
    37         String code = req.getParameter("checkCode");
    38         if (checkCode != null && !checkCode.equalsIgnoreCase(code)) {
    39             req.setAttribute("msg", "验证码错误");
    40             req.getRequestDispatcher("/index.jsp").forward(req, resp);
    41         } else {
    42             //1.2.验证码正确
    43             //2.校验登陆密码
    44             User user = new User();
    45             Map<String, String[]> parameterMap = req.getParameterMap();
    46             //使用BeanUtils工具类封装成JavaBean对象
    47             try {
    48                 BeanUtils.populate(user, parameterMap);
    49             } catch (IllegalAccessException e) {
    50                 e.printStackTrace();
    51             } catch (InvocationTargetException e) {
    52                 e.printStackTrace();
    53             }
    54             UserDao userDao = new UserDao();
    55             User entity = userDao.checkUser(user);
    56             if (entity != null) {
    57                 //2.1.匹配重定向到登录成功 Success.jsp 页面
    58                 session.setAttribute("username", entity.getUsername());
    59                 resp.sendRedirect(req.getContextPath() + "/success.jsp");
    60             } else {
    61                 //2.2.不匹配,转发到登陆界面
    62                 req.setAttribute("msg", "用户名或密码错误");
    63                 req.getRequestDispatcher("/index.jsp").forward(req, resp);
    64             }
    65         }
    66     }
    67 }
    LoginServlet

    3.JavaBean实体类代码

     1 package com.isit.entity;
     2 
     3 /**
     4  * @program: User
     5  * @description: User实体类
     6  * @author: wxh
     7  * @date: 2019-06-11 14:15
     8  **/
     9 public class User {
    10     private String id;
    11     private String username;
    12     private String password;
    13 
    14     public String getId() {
    15         return id;
    16     }
    17 
    18     public void setId(String id) {
    19         this.id = id;
    20     }
    21 
    22     public String getUsername() {
    23         return username;
    24     }
    25 
    26     public void setUsername(String username) {
    27         this.username = username;
    28     }
    29 
    30     public String getPassword() {
    31         return password;
    32     }
    33 
    34     public void setPassword(String password) {
    35         this.password = password;
    36     }
    37 }
    User

    4.UserDao数据库操作层

     1 package com.isit.dao;
     2 
     3 import com.isit.entity.User;
     4 import com.isit.utils.JDBCUtils;
     5 import org.springframework.jdbc.core.JdbcTemplate;
     6 import org.springframework.jdbc.core.RowMapper;
     7 
     8 import java.sql.ResultSet;
     9 import java.sql.SQLException;
    10 
    11 /**
    12  * @program: UserDao
    13  * @description: UserDao
    14  * @author: wxh
    15  * @date: 2019-06-11 14:46
    16  **/
    17 public class UserDao {
    18     JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    19 
    20     public User checkUser(User user){
    21         String sql = "select * from user where username = ? and password = ?";
    22         try{
    23             User entity= jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
    24                 @Override
    25                 public User mapRow(ResultSet resultSet, int i) throws SQLException {
    26                     User user = new User();
    27                     String username = resultSet.getString("username");
    28                     String password = resultSet.getString("password");
    29                     user.setUsername(username);
    30                     user.setPassword(password);
    31                     return user;
    32                 }
    33             },user.getUsername(),user.getPassword());
    34             return entity;
    35         }catch (Exception e){
    36             e.printStackTrace();
    37             return null;
    38         }
    39     }
    40 
    41 }
    UserDao

    5.JDBC工具类

     1 package com.isit.utils;
     2 
     3 import com.alibaba.druid.pool.DruidDataSourceFactory;
     4 
     5 import javax.sql.DataSource;
     6 import java.io.IOException;
     7 import java.io.InputStream;
     8 import java.sql.Connection;
     9 import java.sql.ResultSet;
    10 import java.sql.SQLException;
    11 import java.sql.Statement;
    12 import java.util.Properties;
    13 
    14 /**
    15  * @program: JDBCUtils
    16  * @description: 数据库连接池工具类
    17  * @author: wxh
    18  * @date: 2019-06-11 14:17
    19  **/
    20 public class JDBCUtils {
    21 
    22     private static DataSource ds;
    23     static {
    24         Properties properties = new Properties();
    25         InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
    26         try {
    27             properties.load(resourceAsStream);
    28             ds = DruidDataSourceFactory.createDataSource(properties);
    29         } catch (IOException e) {
    30             e.printStackTrace();
    31         }catch (Exception e) {
    32             e.printStackTrace();
    33         }
    34     }
    35 
    36     public static DataSource getDataSource(){
    37         return ds;
    38     }
    39 
    40     public static Connection getConnection() throws SQLException {
    41         return ds.getConnection();
    42     }
    43 
    44     public static void close(Connection con, Statement statement, ResultSet resultSet){
    45         if(resultSet !=null){
    46             try {
    47                 resultSet.close();
    48             } catch (SQLException e) {
    49                 e.printStackTrace();
    50             }
    51         }
    52         if(statement!=null){
    53             try {
    54                 statement.close();
    55             } catch (SQLException e) {
    56                 e.printStackTrace();
    57             }
    58         }
    59         if(con!=null){
    60             try {
    61                 con.close();
    62             } catch (SQLException e) {
    63                 e.printStackTrace();
    64             }
    65         }
    66     }
    67 
    68     public static void close(Connection connection,Statement statement){
    69         close(connection,statement,null);
    70     }
    71 
    72 }
    JDBCUtils

    6.JSP页面

     1 <%--
     2   Created by IntelliJ IDEA.
     3   User: isit
     4   Date: 2019/6/11
     5   Time: 14:09
     6   To change this template use File | Settings | File Templates.
     7 --%>
     8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     9 <html>
    10   <head>
    11     <title>登陆</title>
    12     <script>
    13       window.onload= function () {
    14         document.getElementById("img").onclick=function () {
    15           this.src = "/loginJsp/checkCodeServlet?time="+ new Date().getTime();
    16         }
    17       }
    18     </script>
    19   </head>
    20 
    21   <body>
    22   <form method="post" action="/loginJsp/loginServlet">
    23     <div>登录名:<input type="text" name="username"></div>
    24     <div>密  码:<input type="password" name="password"></div>
    25     <div><img src="/loginJsp/checkCodeServlet" id="img"></div>
    26     <div> <input type="text" name="checkCode"></div>
    27     <div><input type="submit"></div>
    28   </form>
    29   <div><%=request.getAttribute("msg")%></div>
    30   </body>
    31 </html>
    index.jsp
     1 <%--
     2   Created by IntelliJ IDEA.
     3   User: isit
     4   Date: 2019/6/11
     5   Time: 16:11
     6   To change this template use File | Settings | File Templates.
     7 --%>
     8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     9 <html>
    10 <head>
    11     <title>登陆成功</title>
    12 </head>
    13 <body>
    14 <h1>
    15     <%=request.getSession().getAttribute("username")%> ,登陆成功
    16 </h1>
    17 </body>
    18 </html>
    success.jsp

    总结:

    1.实现登陆操作需要验证码Servlet和登陆Servlet两个Servlet,一个会话中需要请求两次,一个生成验证码图片,一个做验证操作(验证码匹配和登陆账号密码匹配);

    2.CheckCodeServlet生成验证码图片到index.jsp页面,并将生成的验证码存到session中,以供LoginServlet做验证码验证操作;

    3.LoginServlet需要两步验证,(1)验证验证码(2)验证登陆名和密码

    3.1.通过HttpServletRequst对象获取Session对象,从Session对象中获取CheckCodeServlet添加到session中的验证码,以做验证操作,成功,继续下一步的登陆名和密码操作,失败,转发到登陆index.jsp页面,提示验证码错误;

    3.2.验证码校验通过后,通过Dao层操作数据库返回查询结果(使用Druid数据库连接池,并使用JDBCTemple对数据库连接池对象进行封装,执行queryForObject方法返回实体类User)

    3.3.校验通过,设置登陆名到session中(setAttribute),重定向到success.jsp页面,jsp页面取session中存放的登录名,展示XXX,登陆成功;

    3.4.校验失败,转发到index.jsp页面中,提示登陆名密码错误。

  • 相关阅读:
    在WinForm应用程序中快速实现多语言的处理
    使用EasyNetQ组件操作RabbitMQ消息队列服务
    在GridControl表格控件中实现多层级主从表数据的展示
    在Winform混合式框架中整合外部API接口的调用
    快看Sample代码,速学Swift语言(3)-运算符
    快看Sample代码,速学Swift语言(1)-语法速览
    基于信封套打以及批量打印的实现过程
    Winform界面中实现通用工具栏按钮的事件处理
    Winform界面中实现菜单列表的动态个性化配置管理
    双指针模板
  • 原文地址:https://www.cnblogs.com/isit/p/11004766.html
Copyright © 2011-2022 走看看