• 【JavaWeb】注册页面验证码,用户名已存在,密码格式校验


     ✨✨个人主页:沫洺的主页

    📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏 

                               📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏

                               📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏     

    💖💖如果文章对你有所帮助请留下三连✨✨

    🌈注册页面优化

    🎨代码优化

    注册时对数据库中的账号进行查询,提示用户是否存在

    使用第三方工具类生成验证码,并进行校验

    具体优化:

    • 📌同样遵循三层架构的分层思想模式,目的是为了“高内聚低耦合”
    • 📌在util工具包中添加第三方工具类CheckCodeUtil,用来生成验证码图片
    • 📌注册失败(用户名已存在,验证码填写错误,密码不规范)提示信息
    • 📌注册成功跳转登录界面,提示登录成功,进行登录

    🎨Web层

    🔎RegisterServlet

    1. package com.moming.web;
    2. import com.moming.pojo.User;
    3. import com.moming.service.UserService;
    4. import com.moming.util.StandardPasswordUtil;
    5. import javax.servlet.*;
    6. import javax.servlet.http.*;
    7. import javax.servlet.annotation.*;
    8. import java.io.IOException;
    9. @WebServlet("/registerServlet")
    10. public class RegisterServlet extends HttpServlet {
    11. UserService userService= new UserService();
    12. StandardPasswordUtil standardPasswordUtil = new StandardPasswordUtil();
    13. @Override
    14. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    15. //获取数据
    16. String username = request.getParameter("username");
    17. String password = request.getParameter("password");
    18. //获取用户填写的验证码
    19. String checkCode = request.getParameter("checkCode");
    20. //封装数据
    21. User user = new User();
    22. user.setUsername(username);
    23. user.setPassword(password);
    24. //判断密码是否符合规范,调用工具类,判断密码是否是大小写字母、数字、特殊字符中的至少三种
    25. boolean b = standardPasswordUtil.checkPasswordRule(password);
    26. if(!b){
    27. //密码格式错误,跳转到注册页面
    28. request.setAttribute("msg1", "密码格式错误");
    29. //转发
    30. request.getRequestDispatcher("/register.jsp").forward(request,response);
    31. return;
    32. }
    33. //获取服务器域中的验证码
    34. HttpSession session = request.getSession();
    35. String checkCode1 = (String) session.getAttribute("checkCode");
    36. //如果填写的验证码不一致直接退出,不再执行下面的代码
    37. if(!checkCode.equalsIgnoreCase(checkCode1)){
    38. //验证码不一致,跳转到注册页面
    39. request.setAttribute("msg", "验证码填写错误");
    40. //转发
    41. request.getRequestDispatcher("/register.jsp").forward(request,response);
    42. return;
    43. }
    44. //调用service层
    45. boolean f = userService.register(user);
    46. if(f){
    47. //注册成功,跳转到登录页面
    48. request.setAttribute("msg", "注册成功,请登录");
    49. //转发
    50. request.getRequestDispatcher("/login.jsp").forward(request,response);
    51. }else {
    52. //注册失败,跳转到注册页面
    53. request.setAttribute("msg", "用户名已存在");
    54. //转发
    55. request.getRequestDispatcher("/register.jsp").forward(request,response);
    56. }
    57. }
    58. @Override
    59. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    60. doGet(request, response);
    61. }
    62. }

    🔎CheckCodeServlet

    1. package com.moming.web;
    2. import com.moming.util.CheckCodeUtil;
    3. import javax.servlet.*;
    4. import javax.servlet.http.*;
    5. import javax.servlet.annotation.*;
    6. import java.io.IOException;
    7. @WebServlet("/checkCodeServlet")
    8. public class CheckCodeServlet extends HttpServlet {
    9. @Override
    10. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    11. //生成验证码
    12. ServletOutputStream os = response.getOutputStream();
    13. String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
    14. //存入session中
    15. HttpSession session = request.getSession();
    16. session.setAttribute("checkCode",checkCode);
    17. }
    18. @Override
    19. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    20. doGet(request, response);
    21. }
    22. }

    🎨Service层

    🔎UserService

    1. package com.moming.service;
    2. import com.moming.mapper.UserMapper;
    3. import com.moming.pojo.User;
    4. import com.moming.util.SqlSessionFactoryUtils;
    5. import org.apache.ibatis.session.SqlSession;
    6. import org.apache.ibatis.session.SqlSessionFactory;
    7. public class UserService {
    8. //通过工具类获取工厂对象
    9. SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    10. public User login(String username,String password){
    11. //获取sqlSession
    12. SqlSession sqlSession = sqlSessionFactory.openSession();
    13. //获取mapper
    14. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    15. //调用dao层
    16. User user = mapper.selectUser(username, password);
    17. sqlSession.close();
    18. return user;
    19. }
    20. public boolean register(User user){
    21. //获取sqlSession
    22. SqlSession sqlSession = sqlSessionFactory.openSession();
    23. //获取mapper
    24. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    25. //调用dao层
    26. User user1 = mapper.selectUserName(user.getUsername());
    27. //判断用户是否已存在,不存在就可以注册
    28. if(user1==null){
    29. mapper.insertUser(user);
    30. sqlSession.commit();
    31. sqlSession.close();
    32. }
    33. return user1==null;
    34. }
    35. }

    🎨util工具包

    🔎CheckCodeUtil

    1. package com.moming.util;
    2. import javax.imageio.ImageIO;
    3. import java.awt.*;
    4. import java.awt.geom.AffineTransform;
    5. import java.awt.image.BufferedImage;
    6. import java.io.File;
    7. import java.io.FileOutputStream;
    8. import java.io.IOException;
    9. import java.io.OutputStream;
    10. import java.util.Arrays;
    11. import java.util.Random;
    12. /**
    13. * 生成验证码工具类
    14. */
    15. public class CheckCodeUtil {
    16. public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    17. private static Random random = new Random();
    18. /**
    19. * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
    20. *
    21. * @param width 图片宽度
    22. * @param height 图片高度
    23. * @param os 输出流
    24. * @param verifySize 数据长度
    25. * @return 验证码数据
    26. * @throws IOException
    27. */
    28. public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
    29. String verifyCode = generateVerifyCode(verifySize);
    30. outputImage(width, height, os, verifyCode);
    31. return verifyCode;
    32. }
    33. /**
    34. * 使用系统默认字符源生成验证码
    35. *
    36. * @param verifySize 验证码长度
    37. * @return
    38. */
    39. public static String generateVerifyCode(int verifySize) {
    40. return generateVerifyCode(verifySize, VERIFY_CODES);
    41. }
    42. /**
    43. * 使用指定源生成验证码
    44. *
    45. * @param verifySize 验证码长度
    46. * @param sources 验证码字符源
    47. * @return
    48. */
    49. public static String generateVerifyCode(int verifySize, String sources) {
    50. // 未设定展示源的字码,赋默认值大写字母+数字
    51. if (sources == null || sources.length() == 0) {
    52. sources = VERIFY_CODES;
    53. }
    54. int codesLen = sources.length();
    55. Random rand = new Random(System.currentTimeMillis());
    56. StringBuilder verifyCode = new StringBuilder(verifySize);
    57. for (int i = 0; i < verifySize; i++) {
    58. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
    59. }
    60. return verifyCode.toString();
    61. }
    62. /**
    63. * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
    64. *
    65. * @param w
    66. * @param h
    67. * @param outputFile
    68. * @param verifySize
    69. * @return
    70. * @throws IOException
    71. */
    72. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
    73. String verifyCode = generateVerifyCode(verifySize);
    74. outputImage(w, h, outputFile, verifyCode);
    75. return verifyCode;
    76. }
    77. /**
    78. * 生成指定验证码图像文件
    79. *
    80. * @param w
    81. * @param h
    82. * @param outputFile
    83. * @param code
    84. * @throws IOException
    85. */
    86. public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
    87. if (outputFile == null) {
    88. return;
    89. }
    90. File dir = outputFile.getParentFile();
    91. //文件不存在
    92. if (!dir.exists()) {
    93. //创建
    94. dir.mkdirs();
    95. }
    96. try {
    97. outputFile.createNewFile();
    98. FileOutputStream fos = new FileOutputStream(outputFile);
    99. outputImage(w, h, fos, code);
    100. fos.close();
    101. } catch (IOException e) {
    102. throw e;
    103. }
    104. }
    105. /**
    106. * 输出指定验证码图片流
    107. *
    108. * @param w
    109. * @param h
    110. * @param os
    111. * @param code
    112. * @throws IOException
    113. */
    114. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
    115. int verifySize = code.length();
    116. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    117. Random rand = new Random();
    118. Graphics2D g2 = image.createGraphics();
    119. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    120. // 创建颜色集合,使用java.awt包下的类
    121. Color[] colors = new Color[5];
    122. Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
    123. Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
    124. Color.PINK, Color.YELLOW};
    125. float[] fractions = new float[colors.length];
    126. for (int i = 0; i < colors.length; i++) {
    127. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
    128. fractions[i] = rand.nextFloat();
    129. }
    130. Arrays.sort(fractions);
    131. // 设置边框色
    132. g2.setColor(Color.GRAY);
    133. g2.fillRect(0, 0, w, h);
    134. Color c = getRandColor(200, 250);
    135. // 设置背景色
    136. g2.setColor(c);
    137. g2.fillRect(0, 2, w, h - 4);
    138. // 绘制干扰线
    139. Random random = new Random();
    140. // 设置线条的颜色
    141. g2.setColor(getRandColor(160, 200));
    142. for (int i = 0; i < 20; i++) {
    143. int x = random.nextInt(w - 1);
    144. int y = random.nextInt(h - 1);
    145. int xl = random.nextInt(6) + 1;
    146. int yl = random.nextInt(12) + 1;
    147. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
    148. }
    149. // 添加噪点
    150. // 噪声率
    151. float yawpRate = 0.05f;
    152. int area = (int) (yawpRate * w * h);
    153. for (int i = 0; i < area; i++) {
    154. int x = random.nextInt(w);
    155. int y = random.nextInt(h);
    156. // 获取随机颜色
    157. int rgb = getRandomIntColor();
    158. image.setRGB(x, y, rgb);
    159. }
    160. // 添加图片扭曲
    161. shear(g2, w, h, c);
    162. g2.setColor(getRandColor(100, 160));
    163. int fontSize = h - 4;
    164. Font font = new Font("Algerian", Font.ITALIC, fontSize);
    165. g2.setFont(font);
    166. char[] chars = code.toCharArray();
    167. for (int i = 0; i < verifySize; i++) {
    168. AffineTransform affine = new AffineTransform();
    169. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
    170. g2.setTransform(affine);
    171. g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
    172. }
    173. g2.dispose();
    174. ImageIO.write(image, "jpg", os);
    175. }
    176. /**
    177. * 随机颜色
    178. *
    179. * @param fc
    180. * @param bc
    181. * @return
    182. */
    183. private static Color getRandColor(int fc, int bc) {
    184. if (fc > 255) {
    185. fc = 255;
    186. }
    187. if (bc > 255) {
    188. bc = 255;
    189. }
    190. int r = fc + random.nextInt(bc - fc);
    191. int g = fc + random.nextInt(bc - fc);
    192. int b = fc + random.nextInt(bc - fc);
    193. return new Color(r, g, b);
    194. }
    195. private static int getRandomIntColor() {
    196. int[] rgb = getRandomRgb();
    197. int color = 0;
    198. for (int c : rgb) {
    199. color = color << 8;
    200. color = color | c;
    201. }
    202. return color;
    203. }
    204. private static int[] getRandomRgb() {
    205. int[] rgb = new int[3];
    206. for (int i = 0; i < 3; i++) {
    207. rgb[i] = random.nextInt(255);
    208. }
    209. return rgb;
    210. }
    211. private static void shear(Graphics g, int w1, int h1, Color color) {
    212. shearX(g, w1, h1, color);
    213. shearY(g, w1, h1, color);
    214. }
    215. private static void shearX(Graphics g, int w1, int h1, Color color) {
    216. int period = random.nextInt(2);
    217. boolean borderGap = true;
    218. int frames = 1;
    219. int phase = random.nextInt(2);
    220. for (int i = 0; i < h1; i++) {
    221. double d = (double) (period >> 1)
    222. * Math.sin((double) i / (double) period
    223. + (6.2831853071795862D * (double) phase)
    224. / (double) frames);
    225. g.copyArea(0, i, w1, 1, (int) d, 0);
    226. if (borderGap) {
    227. g.setColor(color);
    228. g.drawLine((int) d, i, 0, i);
    229. g.drawLine((int) d + w1, i, w1, i);
    230. }
    231. }
    232. }
    233. private static void shearY(Graphics g, int w1, int h1, Color color) {
    234. int period = random.nextInt(40) + 10; // 50;
    235. boolean borderGap = true;
    236. int frames = 20;
    237. int phase = 7;
    238. for (int i = 0; i < w1; i++) {
    239. double d = (double) (period >> 1)
    240. * Math.sin((double) i / (double) period
    241. + (6.2831853071795862D * (double) phase)
    242. / (double) frames);
    243. g.copyArea(i, 0, 1, h1, 0, (int) d);
    244. if (borderGap) {
    245. g.setColor(color);
    246. g.drawLine(i, (int) d, i, 0);
    247. g.drawLine(i, (int) d + h1, i, h1);
    248. }
    249. }
    250. }
    251. }

    🔎StandardPasswordUtil

    1. package com.moming.util;
    2. public class StandardPasswordUtil {
    3. //数字
    4. public static final String REG_NUMBER = ".*\\d+.*";
    5. //小写字母
    6. public static final String REG_UPPERCASE = ".*[A-Z]+.*";
    7. //大写字母
    8. public static final String REG_LOWERCASE = ".*[a-z]+.*";
    9. //特殊符号
    10. public static final String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";
    11. public static boolean checkPasswordRule(String password) {
    12. //密码为空或者长度小于8位则返回false
    13. if (password == null || password.length() < 8) return false;
    14. int i = 0;
    15. if (password.matches(REG_NUMBER)) i++;
    16. if (password.matches(REG_LOWERCASE)) i++;
    17. if (password.matches(REG_UPPERCASE)) i++;
    18. if (password.matches(REG_SYMBOL)) i++;
    19. if (i < 3) return false;
    20. return true;
    21. }
    22. }

    🎨前端代码

    🔎register.css

    1. * {
    2. margin: 0;
    3. padding: 0;
    4. list-style-type: none;
    5. }
    6. .reg-content{
    7. padding: 20px;
    8. margin: 3px;
    9. }
    10. a, img {
    11. border: 0;
    12. }
    13. body {
    14. background-image: url("../imgs/img.png") ;
    15. text-align: center;
    16. }
    17. table {
    18. border-collapse: collapse;
    19. border-spacing: 0;
    20. }
    21. td, th {
    22. padding: 0;
    23. height: 50px;
    24. }
    25. .inputs{
    26. vertical-align: top;
    27. }
    28. .clear {
    29. clear: both;
    30. }
    31. .clear:before, .clear:after {
    32. content: "";
    33. display: table;
    34. }
    35. .clear:after {
    36. clear: both;
    37. }
    38. .form-div {
    39. background-color: rgba(255, 255, 255, 0.27);
    40. border-radius: 10px;
    41. border: 1px solid #aaa;
    42. width: 424px;
    43. margin-top: 100px;
    44. margin-left:400px;
    45. padding: 30px 0 20px 0px;
    46. font-size: 16px;
    47. box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
    48. text-align: left;
    49. }
    50. #username{
    51. width: 268px;
    52. margin: 10px;
    53. line-height: 20px;
    54. font-size: 16px;
    55. }
    56. #password{
    57. width: 268px;
    58. margin: 10px;
    59. line-height: 20px;
    60. font-size: 16px;
    61. }
    62. #checkCode{
    63. width: 100px;
    64. margin: 10px;
    65. line-height: 20px;
    66. font-size: 16px;
    67. }
    68. .form-div input[type="checkbox"] {
    69. margin: 20px 0 20px 10px;
    70. }
    71. .form-div input[type="button"], .form-div input[type="submit"] {
    72. margin: 10px 20px 0 0;
    73. }
    74. .form-div table {
    75. margin: 0 auto;
    76. text-align: right;
    77. color: rgba(64, 64, 64, 1.00);
    78. }
    79. .form-div table img {
    80. vertical-align: middle;
    81. margin: 0 0 5px 0;
    82. }
    83. .footer {
    84. color: rgba(64, 64, 64, 1.00);
    85. font-size: 12px;
    86. margin-top: 30px;
    87. }
    88. .form-div .buttons {
    89. float: right;
    90. }
    91. input[type="text"], input[type="password"], input[type="email"] {
    92. border-radius: 8px;
    93. box-shadow: inset 0 2px 5px #eee;
    94. padding: 10px;
    95. border: 1px solid #D4D4D4;
    96. color: #333333;
    97. margin-top: 5px;
    98. }
    99. input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
    100. border: 1px solid #50afeb;
    101. outline: none;
    102. }
    103. input[type="button"], input[type="submit"] {
    104. padding: 7px 15px;
    105. background-color: #3c6db0;
    106. text-align: center;
    107. border-radius: 5px;
    108. overflow: hidden;
    109. min-width: 80px;
    110. border: none;
    111. color: #FFF;
    112. box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
    113. }
    114. input[type="button"]:hover, input[type="submit"]:hover {
    115. background-color: #5a88c8;
    116. }
    117. input[type="button"]:active, input[type="submit"]:active {
    118. background-color: #5a88c8;
    119. }
    120. .err_msg{
    121. color: red;
    122. padding-right: 170px;
    123. }
    124. #password_err,#tel_err{
    125. padding-right: 195px;
    126. }
    127. #reg_btn{
    128. margin-right:50px; width: 285px; height: 45px; margin-top:20px;
    129. font-size: 16px;
    130. }
    131. h1{
    132. text-align: center;
    133. }

    🔎register.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>注册title>
    7. <link href="css/register.css" rel="stylesheet">
    8. head>
    9. <body>
    10. <div class="form-div">
    11. <div class="reg-content">
    12. <h1>注册页面h1>
    13. <span>已有帐号点击:span> <a href="login.html">登录a>
    14. div>
    15. <form id="reg-form" action="/moming/registerServlet" method="post">
    16. <table>
    17. <tr>
    18. <td>账号:td>
    19. <td class="inputs">
    20. <input name="username" type="text" id="username">
    21. <br>
    22. <span id="username_err" class="err_msg">${msg}span>
    23. td>
    24. tr>
    25. <tr>
    26. <td>密码:td>
    27. <td class="inputs">
    28. <input name="password" type="password" id="password">
    29. <br>
    30. <span id="password_err" class="err_msg">${msg1}span>
    31. td>
    32. tr>
    33. <tr>
    34. <td>验证码:td>
    35. <td class="inputs">
    36. <input name="checkCode" type="text" id="checkCode">
    37. <img id="img" src="/moming/checkCodeServlet">
    38. <a href="#" id="changeImg">看不清?a>
    39. td>
    40. tr>
    41. table>
    42. <div class="buttons">
    43. <input value="注 册" type="submit" id="reg_btn">
    44. div>
    45. <br class="clear">
    46. form>
    47. div>
    48. <script>
    49. document.getElementById("changeImg").onclick = function () {
    50. /*解决浏览器缓冲问题*/
    51. let milliseconds = new Date().getMilliseconds();
    52. document.getElementById("img").src="/moming/checkCodeServlet?"+milliseconds;
    53. }
    54. script>
    55. body>
    56. html>

    💦 总结说明

    到此登录注册案例差不多已经完成了,后续的案例拓展可以通过SuccessServlet进行拓展,即登录成功后跳转到其他页面页面,在上述优化代码中,主要是对第三方工具的使用,其中在验证码更换图片中,有个url处理就是做了一个时间拼接,目的是为了解决浏览器的缓存,还有就是在密码格式校验使用了正则表达式.

  • 相关阅读:
    #QT(网络文件下载)
    SpringMVC
    10道不得不会的Docker面试题
    记录一次wls2上ubuntu20.04版本中安装docker
    JAVA设计模式8:装饰模式,动态地将责任附加到对象上,扩展对象的功能
    python使用蓝牙库选择
    大数据-之LibrA数据库系统告警处理(ALM-12043 DNS解析时长超过阈值)
    uniapp后台播放音频功能制作
    前端基础向--从项目入手封装公共组件
    儿童台灯哪个品牌比较好?精选央视消费主张推荐的护眼灯
  • 原文地址:https://blog.csdn.net/HeyVIrBbox/article/details/126807473