当前位置:   article > 正文

零基础学JavaWeb开发(十二)之 cookie_javaweb cookie

javaweb cookie

学习cookie,首先我们得先来了解一下什么是会话技术~

什么是会话技术

1.用户打开同一个浏览器,访问到我们的web服务器的资源建立会话,对方断开连接该会话才会结束,在一次会话中可以包含多次请求和响应。通俗易懂的理解:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于用一个浏览器,以便于在同一次会话的多次请求间共享数据。

2.这是因为http协议是无状态的,每次浏览器向服务器请求时,没有绑定会话信息服务器都会认为该请求是为新请求,没有任何记忆功能,所以我们需要会话跟踪技术实现会话内数据共享。

会话技术实现方式

实现方式:      

1.客户端会话跟踪技术:Cookie      

2.服务端会话跟踪技术:Session

3.token或者jwt----新的

十六、cookie

1、什么是Cookie

Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问

Cookie 数据存放在浏览器端(客户端)

2、创建Cookie

1.创建Cookie

Cookie cookie = new Cookie("key","value");

2.使用response响应Cookie给客户端(浏览器)

response.addCookie(cookie);

3.使用response响应Cookie给客户端(浏览器)

  1. Cookie[] cookies = request.getCookies();
  2. cookie.getName();
  3. cookie.getValue();

3、获取Cookie

获取客户端携带的所有Cookie,使用request对象

  1. Cookie[] cookies = request.getCookies();
  2. cookie.getName();
  3. cookie.getValue();
  1. package com.mayikt.servlet;
  2. import jakarta.servlet.ServletException;
  3. import jakarta.servlet.annotation.WebServlet;
  4. import jakarta.servlet.http.Cookie;
  5. import jakarta.servlet.http.HttpServlet;
  6. import jakarta.servlet.http.HttpServletRequest;
  7. import jakarta.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. @WebServlet("/addCookieServlet")
  10. public class AddCookieServlet extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. Cookie cookie = new Cookie("mayikt", "yushengjun");
  14. resp.addCookie(cookie);
  15. }
  16. }
  1. package com.mayikt.servlet;
  2. import jakarta.servlet.ServletException;
  3. import jakarta.servlet.annotation.WebServlet;
  4. import jakarta.servlet.http.Cookie;
  5. import jakarta.servlet.http.HttpServlet;
  6. import jakarta.servlet.http.HttpServletRequest;
  7. import jakarta.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. @WebServlet("/getCookieServlet")
  10. public class GetCookieServlet extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. Cookie[] cookies = req.getCookies();
  14. for (int i = 0; i < cookies.length; i++) {
  15. Cookie cookie = cookies[i];
  16. System.out.println("key:" + cookie.getName() + "," +cookie.getValue());
  17. }
  18. }
  19. }

在没有清理浏览器缓存的情况下?请问重启tomcat服务器?cookie数据会丢失吗?

不会的

4、Cookie的原理解析

基本实现原理

Cookie实现是基于HTTP协议的

1.响应头:set—cookie

客户端(浏览器端)发送请求达到服务器端,服务器端会创建cookie,会将该cookie数据

返回给客户端,在响应头中设置 set—cookie value cookie数据。

2.请求头:cookie

同一个浏览器发送请求时,在请求中设置该cookie数据 存放在请求头中。

cookie value

Cookie过期时间

setMaxAge(int seconds):设置Cookie存活时间

1.正数:将Cookie写入浏览器所在的电脑硬盘,持久化存储,到期自动删除 

2.负数:默认值,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁。

3.零:删除对应Cookie

5、session使用

1.服务器端会话跟踪技术:将数据保存在服务器端

底层基于cookie实现封装的

2.常用的API:

2.1 void session.setAttribute(k,v) session存入值 key=name,value 'yushengjun'

2.2 Object session.getAttribute(k) 获取到session中的值

2.3 void removeAttribute(k) 删除我们的session

6、session原理

1.当我们客户端发送请求达到服务器端时创建session,会得到一个sessionid,在将该

sessionid 响应在响应头<sessionid >

2.客户端(浏览器)接受响应头中的sessionid ,会将该sessionid的值 存放在浏览器中。

session本质上就是基于cookie实现封装的。

3.使用同一个浏览器发送请求时,访问通一个服务器端,会在请求头中设定该sessionid 的值,服务器端就会从请求头中获取到该sessionid 查找对应session。

session 数据存放在服务器端 cookie将数据存放在本地。

7、session细节

1.当客户端关闭后,服务器不关闭的话,获取到的session是否是同一个。因为客户端关闭后,cookie对象被销毁,客户端请求服务器会创建新的session。如果需要相同,可以设置cookie的最大存活时间,让cookie持久化保存两次获取Session是否为同一个

2.在默认情况下,不是同一个。如果需要两个Session相同,则可以创建一个Cookie对象,key为:JSESSIONID,设置一下最大存活时间,让Cookie持久化保存Session的ID,就可以实现客户端关闭,两次获取Session就是同一个。

  1. Cookie c = new Cookie("JSESSIONID",session.getId());
  2. c.setMaxAge(60*60); //1个小时有效期
  3. response.addCookie(c);

2.客户端不关闭,服务器关闭后的话,两次获取的Session是同一个吗?

不是同一个,但是为了确保数据不丢失,因为同样服务器关闭后session对象会被销毁 ,如果想确保数据不丢失,可以使session钝化,即在服务器正常关闭之前,将session对象序列化到硬盘上。下次在服务器启动后,将session文件反序列化转化为内存中的session对象即可。

0D202066E021E4F4FB978F1647C0D742

tomcat自动完成以下工作:

1.session的钝化:在服务器正常关闭之前,将session对象系列化到硬盘上。

2.session的活化: 在服务器启动后,将session文件转化为内存中的session对象即可。

3.session什么时候被销毁?

1.服务器关闭;

2.session对象调用invalidate() ;

3.session默认失效时间 30分钟。

token---

8、session与cookie区别

1.session用于存储一次会话的多次请求的数据,存在服务器端;

2.session可以存储任意类型,任意大小的数据。

session与Cookie的区别:

1.session存储数据在服务器端,Cookie在客户端;

2.session没有数据大小限制,Cookie有数据大小限制;

3.session数据安全,Cookie相对于不安全。

9、用户登录注册案例

9.1、用户登录

使用session保存用户会话信息。

数据库访问层

  1. package com.mayikt.dao;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.utils.MayiktJdbcUtils;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. public class MayikUsertDao {
  8. /**
  9. * 用户登录成功之后 该方法返回 用户登录成功之后对象
  10. */
  11. public MayiktUserEntity login(String userName, String userPwd) {
  12. try {
  13. Connection connection = MayiktJdbcUtils.getConnection();
  14. String loginSql = "select * from mayikt_users where userName=? and userPwd=?;";
  15. PreparedStatement preparedStatement = connection.prepareStatement(loginSql);
  16. preparedStatement.setString(1, userName);
  17. preparedStatement.setString(2, userPwd);
  18. ResultSet resultSet = preparedStatement.executeQuery();
  19. if (!resultSet.next()) { // 查询不到用户数据
  20. return null;
  21. }
  22. // 将db中数据 返回给客户端 查询到数据
  23. Integer id = resultSet.getInt(1);
  24. String dbUserName = resultSet.getString(2);
  25. String dbUserPwd = resultSet.getString(3);
  26. MayiktUserEntity mayiktUserEntity = new MayiktUserEntity(id, dbUserName, dbUserPwd);
  27. return mayiktUserEntity;
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. return null;
  31. }
  32. }
  33. }

业务逻辑层

  1. package com.mayikt.service;
  2. import com.mayikt.dao.MayikUsertDao;
  3. import com.mayikt.entity.MayiktUserEntity;
  4. public class MayikUsertService {
  5. private MayikUsertDao mayikUsertDao = new MayikUsertDao();
  6. public MayiktUserEntity login(String userName, String userPwd) {
  7. return mayikUsertDao.login(userName, userPwd);
  8. }
  9. }

视图层

  1. package com.mayikt.servlet;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.service.MayikUsertService;
  4. import jakarta.servlet.ServletException;
  5. import jakarta.servlet.annotation.WebServlet;
  6. import jakarta.servlet.http.HttpServlet;
  7. import jakarta.servlet.http.HttpServletRequest;
  8. import jakarta.servlet.http.HttpServletResponse;
  9. import jakarta.servlet.http.HttpSession;
  10. import org.apache.commons.lang3.StringUtils;
  11. import java.io.IOException;
  12. @WebServlet("/login")
  13. public class LoginServlet extends HttpServlet {
  14. private MayikUsertService mayikUsertService = new MayikUsertService();
  15. @Override
  16. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  17. // 转发login页面
  18. req.getRequestDispatcher("login.jsp").forward(req, resp);
  19. }
  20. @Override
  21. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  22. // 点击登录的时候 获取到用户的参数
  23. String userName = req.getParameter("userName");
  24. if (StringUtils.isEmpty(userName)) {
  25. //转发到错误页面
  26. req.setAttribute("errorMsg", "用户名称不能够是为空!");
  27. req.getRequestDispatcher("error.jsp").forward(req, resp);
  28. return;
  29. }
  30. String userPwd = req.getParameter("userPwd");
  31. // 参数验证
  32. if (StringUtils.isEmpty(userPwd)) {
  33. //转发到错误页面
  34. req.setAttribute("errorMsg", "userPwd不能够是为空!");
  35. req.getRequestDispatcher("error.jsp").forward(req, resp);
  36. return;
  37. }
  38. // 在调用业务逻辑层
  39. MayiktUserEntity mayiktUserEntity = mayikUsertService.login(userName, userPwd);
  40. if (mayiktUserEntity == null) {
  41. // 用户名称或者密码错误!
  42. req.setAttribute("errorMsg", "用户名称或者是密码错误!");
  43. req.getRequestDispatcher("login.jsp").forward(req, resp);
  44. return;
  45. }
  46. // 能够db中查询到对象 登录成功了 将用户数据存放在session中
  47. HttpSession session = req.getSession();
  48. session.setAttribute("user", mayiktUserEntity);
  49. // 在转发到首页(重定向到首页)
  50. // req.getRequestDispatcher("index.jsp").forward(req, resp);
  51. resp.sendRedirect("index.jsp");
  52. }
  53. }
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/6
  5. Time: 17:12
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>登录测试页面</title>
  13. <form action="/mayikt_session_war_exploded/login" method="post">
  14. <label>用户名: </label><input type="text" name="userName"/><br>
  15. <label>&nbsp码&nbsp: </label><input type="password" name="userPwd"/><br>
  16. ${errorMsg}
  17. <input type="submit" value="登录 "/>
  18. </form>
  19. </head>
  20. </html>

相关配置文件

  1. driverClass=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://127.0.0.1:3306/mayikt?serverTimezone=GMT%2B8
  3. user=root
  4. password=root

9.2、记住密码

思路:

用户登录成功之后,会将用户的名称和密码 写入在cookie中,

当我们用户下次登录时,会直接从cookie中获取到数据 回显到

login.jsp中 这样的话就不需要用户重复的数据用户名称和密码。

改造servlet

  1. package com.mayikt.servlet;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.service.MayikUsertService;
  4. import jakarta.servlet.ServletException;
  5. import jakarta.servlet.annotation.WebServlet;
  6. import jakarta.servlet.http.*;
  7. import org.apache.commons.lang3.StringUtils;
  8. import java.io.IOException;
  9. @WebServlet("/login")
  10. public class LoginServlet extends HttpServlet {
  11. private MayikUsertService mayikUsertService = new MayikUsertService();
  12. @Override
  13. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  14. // 转发login页面
  15. req.getRequestDispatcher("login.jsp").forward(req, resp);
  16. }
  17. @Override
  18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19. // 点击登录的时候 获取到用户的参数
  20. String userName = req.getParameter("userName");
  21. if (StringUtils.isEmpty(userName)) {
  22. //转发到错误页面
  23. req.setAttribute("errorMsg", "用户名称不能够是为空!");
  24. req.getRequestDispatcher("error.jsp").forward(req, resp);
  25. return;
  26. }
  27. String userPwd = req.getParameter("userPwd");
  28. // 参数验证
  29. if (StringUtils.isEmpty(userPwd)) {
  30. //转发到错误页面
  31. req.setAttribute("errorMsg", "userPwd不能够是为空!");
  32. req.getRequestDispatcher("error.jsp").forward(req, resp);
  33. return;
  34. }
  35. // 在调用业务逻辑层
  36. MayiktUserEntity mayiktUserEntity = mayikUsertService.login(userName, userPwd);
  37. if (mayiktUserEntity == null) {
  38. // 用户名称或者密码错误!
  39. req.setAttribute("errorMsg", "用户名称或者是密码错误!");
  40. req.getRequestDispatcher("login.jsp").forward(req, resp);
  41. return;
  42. }
  43. // 判断用户是否记住密码
  44. String rememberPassword = req.getParameter("rememberPassword");
  45. if ("on".equals(rememberPassword)) {
  46. // 如果有记住密码则 将密码保存在cookie中
  47. Cookie userNameCookie = new Cookie("userName", userName);
  48. Cookie userPwdCookie = new Cookie("userPwd", userPwd);
  49. resp.addCookie(userNameCookie);
  50. resp.addCookie(userPwdCookie);
  51. }
  52. // 能够db中查询到对象 登录成功了 将用户数据存放在session中
  53. HttpSession session = req.getSession();
  54. session.setAttribute("user", mayiktUserEntity);
  55. // 在转发到首页(重定向到首页)
  56. // req.getRequestDispatcher("index.jsp").forward(req, resp);
  57. resp.sendRedirect("index.jsp");
  58. }
  59. }

改造jsp

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/6
  5. Time: 17:12
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>登录测试页面</title>
  13. <form action="/mayikt_session_war_exploded/login" method="post">
  14. <label>用户名: </label><input type="text" name="userName" value="${cookie.userName.value}"/><br>
  15. <label>&nbsp码&nbsp: </label><input type="password" name="userPwd" value="${cookie.userPwd.value}"/><br>
  16. <label>记住密码: </label><input type="checkbox" name="rememberPassword"/><br>
  17. ${errorMsg}
  18. <input type="submit" value="登录 "/>
  19. </form>
  20. </head>
  21. </html>

9.3、用户注册

数据库访问层

  1. package com.mayikt.dao;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.utils.MayiktJdbcUtils;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. public class MayikUsertDao {
  8. /**
  9. * 用户登录成功之后 该方法返回 用户登录成功之后对象
  10. */
  11. public MayiktUserEntity login(String userName, String userPwd) {
  12. ResultSet resultSet = null;
  13. PreparedStatement preparedStatement = null;
  14. Connection connection = null;
  15. try {
  16. connection = MayiktJdbcUtils.getConnection();
  17. String loginSql = "select * from mayikt_users where userName=? and userPwd=?;";
  18. preparedStatement = connection.prepareStatement(loginSql);
  19. preparedStatement.setString(1, userName);
  20. preparedStatement.setString(2, userPwd);
  21. resultSet = preparedStatement.executeQuery();
  22. if (!resultSet.next()) { // 查询不到用户数据
  23. return null;
  24. }
  25. // 将db中数据 返回给客户端 查询到数据
  26. Integer id = resultSet.getInt(1);
  27. String dbUserName = resultSet.getString(2);
  28. String dbUserPwd = resultSet.getString(3);
  29. MayiktUserEntity mayiktUserEntity = new MayiktUserEntity(id, dbUserName, dbUserPwd);
  30. return mayiktUserEntity;
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. return null;
  34. } finally {
  35. MayiktJdbcUtils.closeConnection(resultSet, preparedStatement, connection);
  36. }
  37. }
  38. public MayiktUserEntity findByUserName(String userName) {
  39. ResultSet resultSet = null;
  40. PreparedStatement preparedStatement = null;
  41. Connection connection = null;
  42. try {
  43. connection = MayiktJdbcUtils.getConnection();
  44. String loginSql = "select * from mayikt_users where userName=?";
  45. preparedStatement = connection.prepareStatement(loginSql);
  46. preparedStatement.setString(1, userName);
  47. resultSet = preparedStatement.executeQuery();
  48. if (!resultSet.next()) { // 查询不到用户数据
  49. return null;
  50. }
  51. // 将db中数据 返回给客户端 查询到数据
  52. Integer id = resultSet.getInt(1);
  53. String dbUserName = resultSet.getString(2);
  54. String dbUserPwd = resultSet.getString(3);
  55. MayiktUserEntity mayiktUserEntity = new MayiktUserEntity(id, dbUserName, dbUserPwd);
  56. return mayiktUserEntity;
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. return null;
  60. } finally {
  61. MayiktJdbcUtils.closeConnection(resultSet, preparedStatement, connection);
  62. }
  63. }
  64. public int register(String userName, String userPwd) {
  65. Connection connection = null;
  66. PreparedStatement preparedStatement = null;
  67. try {
  68. connection = MayiktJdbcUtils.getConnection();
  69. // sql语句写的操作 ----加上事务
  70. MayiktJdbcUtils.beginTransaction(connection); // 开启事务
  71. String insertSql = "INSERT INTO `mayikt`.`mayikt_users` (`id`, `userName`, `userPwd`) VALUES (null, ?, ?);";
  72. preparedStatement = connection.prepareStatement(insertSql);
  73. preparedStatement.setString(1, userName);
  74. preparedStatement.setString(2, userPwd);
  75. int result = preparedStatement.executeUpdate();
  76. // 代码执行没有问题的情况下 则会提交数据
  77. MayiktJdbcUtils.commitTransaction(connection); // 提交事务
  78. return result;
  79. } catch (Exception e) {
  80. // 程序代码报错之后 是需要回滚事务
  81. e.printStackTrace();
  82. MayiktJdbcUtils.rollBackTransaction(connection);// 回滚事务
  83. return 0;
  84. } finally {
  85. MayiktJdbcUtils.closeConnection(preparedStatement, connection);
  86. }
  87. }
  88. }

业务逻辑层

  1. public int register(String userName, String userPwd) {
  2. return mayikUsertDao.register(userName, userPwd);
  3. }
  4. public MayiktUserEntity findByUserName(String userName) {
  5. return mayikUsertDao.findByUserName(userName);
  6. }

视图层

  1. package com.mayikt.servlet;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.service.MayikUsertService;
  4. import jakarta.servlet.ServletException;
  5. import jakarta.servlet.annotation.WebServlet;
  6. import jakarta.servlet.http.HttpServlet;
  7. import jakarta.servlet.http.HttpServletRequest;
  8. import jakarta.servlet.http.HttpServletResponse;
  9. import org.apache.commons.lang3.StringUtils;
  10. import java.io.IOException;
  11. @WebServlet("/register")
  12. public class RegisterServlet extends HttpServlet {
  13. private MayikUsertService mayikUsertService = new MayikUsertService();
  14. @Override
  15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  16. // 转发到register.jsp
  17. req.getRequestDispatcher("register.jsp").forward(req, resp);
  18. }
  19. @Override
  20. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  21. // 转发到注册插入数据
  22. // 点击注册的时候 获取到用户的参数
  23. String userName = req.getParameter("userName");
  24. if (StringUtils.isEmpty(userName)) {
  25. //转发到错误页面
  26. req.setAttribute("errorMsg", "用户名称不能够是为空!");
  27. req.getRequestDispatcher("register.jsp").forward(req, resp);
  28. return;
  29. }
  30. String userPwd = req.getParameter("userPwd");
  31. // 参数验证
  32. if (StringUtils.isEmpty(userPwd)) {
  33. //转发到错误页面
  34. req.setAttribute("errorMsg", "userPwd不能够是为空!");
  35. req.getRequestDispatcher("register.jsp").forward(req, resp);
  36. return;
  37. }
  38. // 用户注册之前根据用户名称查询该用户是否存在如果不存在的情况下才可以注册 如果存在的话就无法注册
  39. MayiktUserEntity dbMayiktUserEntity = mayikUsertService.findByUserName(userName);
  40. if (dbMayiktUserEntity != null) {
  41. req.setAttribute("errorMsg", "该用户" + userName + ",在数据库中存在无法重复注册!");
  42. req.getRequestDispatcher("register.jsp").forward(req, resp);
  43. return;
  44. }
  45. //用户数据注册
  46. int register = mayikUsertService.register(userName, userPwd);
  47. if (register <= 0) {
  48. // 注册失败了 //转发到错误页面
  49. req.setAttribute("errorMsg", "注册失败!");
  50. req.getRequestDispatcher("register.jsp").forward(req, resp);
  51. return;
  52. }
  53. // 注册成功之后就直接重定向到登录请求
  54. resp.sendRedirect("login");
  55. }
  56. }
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/6
  5. Time: 17:12
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>注册页面</title>
  13. <form action="/mayikt_session_war_exploded/register" method="post">
  14. <label>用户名: </label><input type="text" name="userName"/><br>
  15. <label>&nbsp&nbsp&nbsp码: </label><input type="password" name="userPwd"/><br>
  16. <span style="color: red">${errorMsg}</span>
  17. <input type="submit" value="注册"/>
  18. </form>
  19. </head>
  20. </html>

9.4、图形验证码

图形底层实现原理

java支持根据内容生成图片

abcd 企业实际开发中图形验证码工具类 底层细节我们自己去开发的

1.生成图形验证码内容 abch

2.调用java的api 将我们的该内容 生成一张图片abch

3.将该形验证码内容 abch 存放在session中

用户点击注册时:获取用户输入的图形验证码和session中验证码比对 如果一致的情况下

则开始做注册流程。

图形验证码工具类

  1. package com.mayikt.utils;
  2. import jakarta.servlet.http.HttpServletRequest;
  3. import jakarta.servlet.http.HttpServletResponse;
  4. import jakarta.servlet.http.HttpSession;
  5. import java.awt.Color;
  6. import java.awt.Font;
  7. import java.awt.Graphics;
  8. import java.awt.image.BufferedImage;
  9. import java.util.Random;
  10. import javax.imageio.ImageIO;
  11. /**
  12. * 工具类,生成随机验证码
  13. */
  14. public class RandomValidateCode {
  15. public static final String MAYIKT_RANDOMVALIDATECODE = "RandomValidateCode";// 放到session中的key
  16. private Random random = new Random();
  17. private String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
  18. private int width = 100;// 图片宽度
  19. private int height = 26;// 图片高度
  20. private int lineSize = 40;// 干扰线数量
  21. private int stringNum = 4;// 随机产生的字符数量
  22. /*
  23. * 获得字体
  24. */
  25. private Font getFont() {
  26. return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
  27. }
  28. /*
  29. * 获得颜色
  30. */
  31. private Color getRandColor(int fc, int bc) {
  32. if (fc > 255)
  33. fc = 255;
  34. if (bc > 255)
  35. bc = 255;
  36. int r = fc + random.nextInt(bc - fc - 16);
  37. int g = fc + random.nextInt(bc - fc - 14);
  38. int b = fc + random.nextInt(bc - fc - 18);
  39. return new Color(r, g, b);
  40. }
  41. /**
  42. * 生成随机图片
  43. */
  44. public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
  45. HttpSession session = request.getSession();
  46. // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
  47. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  48. Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,该对象可以在图像上进行各种绘制操作
  49. g.fillRect(0, 0, width, height);
  50. g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
  51. g.setColor(getRandColor(110, 133));
  52. // 绘制干扰线
  53. for (int i = 0; i <= lineSize; i++) {
  54. drowLine(g);
  55. }
  56. // 绘制随机字符
  57. String randomString = "";
  58. for (int i = 1; i <= stringNum; i++) {
  59. randomString = drowString(g, randomString, i);
  60. }
  61. session.removeAttribute(MAYIKT_RANDOMVALIDATECODE);
  62. session.setAttribute(MAYIKT_RANDOMVALIDATECODE, randomString);
  63. g.dispose();
  64. try {
  65. ImageIO.write(image, "JPEG", response.getOutputStream());// 将内存中的图片通过流动形式输出到客户端
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. /*
  71. * 绘制字符串
  72. */
  73. private String drowString(Graphics g, String randomString, int i) {
  74. g.setFont(getFont());
  75. g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
  76. String rand = getRandomString(random.nextInt(randString.length()));
  77. randomString += rand;
  78. g.translate(random.nextInt(3), random.nextInt(3));
  79. g.drawString(rand, 13 * i, 16);
  80. return randomString;
  81. }
  82. /*
  83. * 绘制干扰线
  84. */
  85. private void drowLine(Graphics g) {
  86. int x = random.nextInt(width);
  87. int y = random.nextInt(height);
  88. int xl = random.nextInt(13);
  89. int yl = random.nextInt(15);
  90. g.drawLine(x, y, x + xl, y + yl);
  91. }
  92. /*
  93. * 获取随机的字符
  94. */
  95. public String getRandomString(int num) {
  96. return String.valueOf(randString.charAt(num));
  97. }
  98. }
  99. package com.mayikt.servlet;
  100. import jakarta.servlet.ServletException;
  101. import jakarta.servlet.annotation.WebServlet;
  102. import jakarta.servlet.http.HttpServlet;
  103. import jakarta.servlet.http.HttpServletRequest;
  104. import jakarta.servlet.http.HttpServletResponse;
  105. import java.io.IOException;
  106. /**
  107. * 前台验证码处点击刷新,发送到该servlet的请求,
  108. * 该servlet调用生成验证码的工具类返回一个图像验证码
  109. */
  110. @WebServlet(name = "VerifycodeServlet", urlPatterns = "/VerifycodeServlet")
  111. public class VerifycodeServlet extends HttpServlet {
  112. private static final long serialVersionUID = 1L;
  113. public void doGet(HttpServletRequest request, HttpServletResponse response)
  114. throws ServletException, IOException {
  115. response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
  116. response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
  117. //做浏览器兼容
  118. response.setHeader("Cache-Control", "no-cache");
  119. response.setDateHeader("Expire", 0);
  120. RandomValidateCode randomValidateCode = new RandomValidateCode();
  121. try {
  122. randomValidateCode.getRandcode(request, response);//输出图片方法
  123. } catch (Exception e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. public void doPost(HttpServletRequest request, HttpServletResponse response)
  128. throws ServletException, IOException {
  129. doGet(request, response);
  130. }
  131. }

注册jsp加上图形验证码

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/6
  5. Time: 17:12
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>注册页面</title>
  13. <form action="/mayikt_session_war_exploded/register" method="post">
  14. <label>用户名: </label><input type="text" name="userName"/><br>
  15. <label>&nbsp&nbsp&nbsp码: </label><input type="password" name="userPwd"/><br>
  16. <label>验证码: </label><input type="text" name="code"/><img id="exchangecode" src="VerifycodeServlet">
  17. <a id="ecode" href="#">看不清?换一张图片</a><br>
  18. <span style="color: red">${errorMsg}</span>
  19. <input type="submit" value="注册"/>
  20. </form>
  21. <script type="text/javascript">
  22. window.onload = function () {
  23. //获取img标签的对象
  24. img = document.getElementById("exchangecode");
  25. img.onclick = function () {
  26. //加时间戳,避免浏览器缓存
  27. var date = new Date().getTime()
  28. img.src = "VerifycodeServlet?" + date;
  29. }
  30. //获取a标签的对象
  31. ec = document.getElementById("ecode");
  32. ec.onclick = function () {
  33. //加时间戳
  34. var date = new Date().getTime()
  35. img.src = "VerifycodeServlet?" + date;
  36. }
  37. }
  38. </script>
  39. </head>
  40. </html>

注册验证图形验证码

  1. package com.mayikt.servlet;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.service.MayikUsertService;
  4. import com.mayikt.utils.RandomValidateCode;
  5. import jakarta.servlet.ServletException;
  6. import jakarta.servlet.annotation.WebServlet;
  7. import jakarta.servlet.http.HttpServlet;
  8. import jakarta.servlet.http.HttpServletRequest;
  9. import jakarta.servlet.http.HttpServletResponse;
  10. import jakarta.servlet.http.HttpSession;
  11. import org.apache.commons.lang3.StringUtils;
  12. import java.io.IOException;
  13. @WebServlet("/register")
  14. public class RegisterServlet extends HttpServlet {
  15. private MayikUsertService mayikUsertService = new MayikUsertService();
  16. @Override
  17. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  18. // 转发到register.jsp
  19. req.getRequestDispatcher("register.jsp").forward(req, resp);
  20. }
  21. @Override
  22. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. // 转发到注册插入数据
  24. // 点击注册的时候 获取到用户的参数
  25. String userName = req.getParameter("userName");
  26. if (StringUtils.isEmpty(userName)) {
  27. //转发到错误页面
  28. req.setAttribute("errorMsg", "用户名称不能够是为空!");
  29. req.getRequestDispatcher("register.jsp").forward(req, resp);
  30. return;
  31. }
  32. String userPwd = req.getParameter("userPwd");
  33. // 参数验证
  34. if (StringUtils.isEmpty(userPwd)) {
  35. //转发到错误页面
  36. req.setAttribute("errorMsg", "userPwd不能够是为空!");
  37. req.getRequestDispatcher("register.jsp").forward(req, resp);
  38. return;
  39. }
  40. // 图形验证码 比较 是在 注册之前
  41. // 比较图形验证码
  42. String userCode = req.getParameter("code"); // 用户输入的图形验证码
  43. // 从session中获取图形验证码
  44. HttpSession session = req.getSession();
  45. String sessionCode = (String) session.getAttribute(RandomValidateCode.MAYIKT_RANDOMVALIDATECODE);
  46. if (!sessionCode.equalsIgnoreCase(userCode)) {
  47. req.setAttribute("errorMsg", "图形验证码不正确,请重新输入!");
  48. req.getRequestDispatcher("register.jsp").forward(req, resp);
  49. return;
  50. }
  51. // 用户注册之前根据用户名称查询该用户是否存在如果不存在的情况下才可以注册 如果存在的话就无法注册
  52. MayiktUserEntity dbMayiktUserEntity = mayikUsertService.findByUserName(userName);
  53. if (dbMayiktUserEntity != null) {
  54. req.setAttribute("errorMsg", "该用户" + userName + ",在数据库中存在无法重复注册!");
  55. req.getRequestDispatcher("register.jsp").forward(req, resp);
  56. return;
  57. }
  58. //用户数据注册
  59. int register = mayikUsertService.register(userName, userPwd);
  60. if (register <= 0) {
  61. // 注册失败了 //转发到错误页面
  62. req.setAttribute("errorMsg", "注册失败!");
  63. req.getRequestDispatcher("register.jsp").forward(req, resp);
  64. return;
  65. }
  66. // 注册成功之后就直接重定向到登录请求
  67. resp.sendRedirect("login");
  68. }
  69. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/178762
推荐阅读
相关标签
  

闽ICP备14008679号