Session实现验证码登陆笔记

Myth丶恋晨 2021-11-23 09:50 436阅读 0赞

1.生成验证码Servlet

ContractedBlock.gif ExpandedBlockStart.gif

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

CheckCodeServlet

2.登陆Servlet

ContractedBlock.gif ExpandedBlockStart.gif

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

LoginServlet

3.JavaBean实体类代码

ContractedBlock.gif ExpandedBlockStart.gif

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

User

4.UserDao数据库操作层

ContractedBlock.gif ExpandedBlockStart.gif

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

UserDao

5.JDBC工具类

ContractedBlock.gif ExpandedBlockStart.gif

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

JDBCUtils

6.JSP页面

ContractedBlock.gif ExpandedBlockStart.gif

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

index.jsp

ContractedBlock.gif ExpandedBlockStart.gif

  1. 1 <%--
  2. 2 Created by IntelliJ IDEA.
  3. 3 User: isit
  4. 4 Date: 2019/6/11
  5. 5 Time: 16:11
  6. 6 To change this template use File | Settings | File Templates.
  7. 7 --%>
  8. 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. 9 <html>
  10. 10 <head>
  11. 11 <title>登陆成功</title>
  12. 12 </head>
  13. 13 <body>
  14. 14 <h1>
  15. 15 <%=request.getSession().getAttribute("username")%> ,登陆成功
  16. 16 </h1>
  17. 17 </body>
  18. 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页面中,提示登陆名密码错误。

转载于:https://www.cnblogs.com/isit/p/11004766.html

发表评论

表情:
评论列表 (有 0 条评论,436人围观)

还没有评论,来说两句吧...

相关阅读