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

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页面中,提示登陆名密码错误。

Session实现验证码登陆笔记的更多相关文章

  1. JavaWeb-SpringSecurity使用短信验证码登陆

    相关博文 JavaWeb-SpringBoot_一个类实现腾讯云SDK发送短信 传送门 系列博文 项目已上传至guthub 传送门 JavaWeb-SpringSecurity初认识 传送门 Java ...

  2. SpringSceurity(5)---短信验证码登陆功能

    SpringSceurity(5)---短信验证码登陆功能 有关SpringSceurity系列之前有写文章 1.SpringSecurity(1)---认证+授权代码实现 2.SpringSecur ...

  3. web自动化测试中绕开验证码登陆的方式

    web自动化测试中登陆需验证码是很大的一个困扰.现推荐一种简单的避开验证码登陆的方式,先代码进入登录页,人工输入验证码登录后浏览器自动保存cookie,再在新的标签中登录. 具体代码如下: publi ...

  4. Web UI自动化测试中绕开验证码登陆方式浅谈

    web自动化测试中让测试者感到困惑的是登陆验证码,每次都不一样.现在推荐一种绕开验证码登陆的方式,其实就是将web浏览器获取的登陆cookie加载到程序中就可以了,这样程序就会认为你已经登陆,就可以跳 ...

  5. 用Session实现验证码

    新建一个 ashx 一般处理程序 如: YZM.ashx继承接口 IRequiresSessionState //在一般处理程序里面继承 HttpContext context 为请求上下文,包含此次 ...

  6. Session、Cookie 学习笔记

    在开始今天的博文之前首先为自己庆祝一下自己有了三个粉丝,也有了同僚的评论,说实话因为这个开心了好久!哈哈,好了在开始今天的正题之前,首先大家需要了解以下几点: a. HTTP 协议是无状态的协议,WE ...

  7. PHP会话(Session)实现用户登陆功能 转自#落人间#

    对比起 Cookie,Session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制,本文简单介绍 Session 的使用. 由于 Session 是以文本文件形式存储在 ...

  8. 通过cookies跳过验证码登陆页面,直接访问网站的其它URL

    我每次手动访问去NN网的一家酒店,就不需要登陆,一旦我用脚本打开就会让我登陆,而登陆页面又有验证码,不想识别验证码,所以就想:“通过cookies跳过验证码登陆页面,直接访问网站的其它URL”   转 ...

  9. Spring Cloud OAuth2(二) 扩展登陆方式:账户密码登陆、 手机验证码登陆、 二维码扫码登陆

    概要 基于上文讲解的spring cloud 授权服务的搭建,本文扩展了spring security 的登陆方式,增加手机验证码登陆.二维码登陆. 主要实现方式为使用自定义filter. Authe ...

随机推荐

  1. Spring Boot 之 Redis

    一.pom.xml引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...

  2. hibernate的get方法和load方法区别

    读者需注意:Hibernate版本不同,运行机制不太一样,以下是hibernate3.x作为讲解 get方法: Hibernate会确认一下该id对应的数据是否存在,首先在session缓存中查找,然 ...

  3. JavaBean简介和要求

    JavaBean是一种Java语言写成的可重用组件. 所谓javaBean,是指符合如下标准的Java类: 类是公共的 有一个无参的公共的构造器 有属性,且有对应的get.set方法 用户可以使用Ja ...

  4. 高性能JavaScript模板引擎实现原理详解

    这篇文章主要介绍了JavaScript模板引擎实现原理详解,本文着重讲解artTemplate模板的实现原理,它采用预编译方式让性能有了质的飞跃,是其它知名模板引擎的25.32 倍,需要的朋友可以参考 ...

  5. jvm学习(2)JVM内存说明

    前言 一.类方法 类方法是静态方法,前面需要有static修饰符修饰.类方法内不能涉及有关变量的内容1.不能调用类的对象方法2.不能引用对象变量3.类方法不能被重写(覆盖)4.类方法不能使用super ...

  6. Linux基于Hadoop2.8.0集群安装配置Hive2.1.1及基础操作

    前言 安装Apache Hive前提是要先安装hadoop集群,并且hive只需要在hadoop的namenode节点集群里安装即可,安装前需保证Hadoop已启(动文中用到了hadoop的hdfs命 ...

  7. 总结const、readonly、static三者的区别【收藏、转载】20190614

    总结const.readonly.static三者的区别 const:静态常量,也称编译时常量(compile-time constants),属于类型级,通过类名直接访问,被所有对象共享! a.叫编 ...

  8. linux命令中chmod 777 以及drwxr-xr-x分别代表什么意思

    最近跟一个运维人员学了点新东西,感觉以前没怎么注意,但现在感觉很有用,特来记录一下. linux使用==ll==命令列出列表的时候,前面总是有一堆drwxr-xr-x ,这些代表什么意思从来还没有去在 ...

  9. git路径超长 及gitignore

    1 忽略路径超长 git config --system core.longpaths true 2 比较全的gitignore https://www.gitignore.io/api/vim,no ...

  10. Angular 一个简单的指令实现 阻止事件扩散

    //指令定义 @Directive({ selector: `click-stop-propagation` events: 'stopClick($event)' }) class ClickSto ...