Hutool 验证码案例
目录
- Hutool 验证码案例
- 项目结构
- 所学jar包
- 生成验证码业务逻辑
- 登录业务逻辑
- 登录页面login.html
项目结构
所学jar包
hutool、fastjson
生成验证码业务逻辑
package com.bjpowernode.code;import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/imagecode")
public class ImageCodeServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//创建验证码对象LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50, 4, 10);//获取验证码字符串String code = lineCaptcha.getCode();//将验证码 放入到session中req.getSession().setAttribute("code",code);//将验证码输出lineCaptcha.write(resp.getOutputStream());}
}
登录业务逻辑
package com.bjpowernode.login;import com.alibaba.fastjson.JSON;
import com.bjpowernode.result.JSONResult;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;@WebServlet("/login")
public class LoginServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置post请求乱码req.setCharacterEncoding("utf-8");//设置响应的数据格式resp.setContentType("application/json;charset=utf-8");JSONResult jsonResult = new JSONResult();PrintWriter writer = resp.getWriter();String username = req.getParameter("username");String pwd = req.getParameter("pwd");String code = req.getParameter("code");if(code==null||code.equals("")){jsonResult.mark("验证码不能为空");writer.write(JSON.toJSONString(jsonResult));return;}// 获取服务器端保存的验证码String sessionCode = (String) req.getSession().getAttribute("code");if(sessionCode==null||sessionCode.equals("")){jsonResult.mark("验证码错误");writer.write(JSON.toJSONString(jsonResult));return;}if(!sessionCode.equalsIgnoreCase(code)){jsonResult.mark("验证码错误");writer.write(JSON.toJSONString(jsonResult));return;}if(username==null||username.equals("")){jsonResult.mark("账号不能为空");writer.write(JSON.toJSONString(jsonResult));return;}if(pwd ==null||pwd .equals("")){jsonResult.mark("密码不能为空");writer.write(JSON.toJSONString(jsonResult));return;}if(!username.equals("admin")&&pwd.equals("123")){jsonResult.mark("登录失败");writer.write(JSON.toJSONString(jsonResult));return;}writer.write(JSON.toJSONString(jsonResult));}
}
成功失败返回结果类
package com.bjpowernode.result;public class JSONResult {private boolean success = true;private String errorMsg;public JSONResult mark(String msg){this.errorMsg = msg;this.success = false;return this;}public boolean isSuccess() {return success;}public String getErrorMsg() {return errorMsg;}
}
登录页面login.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="js/jquery-3.6.1.js"></script>
</head>
<body>
<form id="formId" action="/login" method="post">姓名:<input type="text" name="username"/><br/>密码:<input type="password" name="pwd"/><br/>验证码:<input type="text" name="code"/><img src="/imagecode" width="100px" onclick="changeCode(this)"><br><span style="color: red" id="tip"></span><input id="btnId" type="button" value="登录"></form>
</body>
<script>// $(function () {// console.log(1);// var serialize = $("#formId").serialize();// console.log(serialize);// console.log("----------------------")// var serializeArray = $("#formId").serializeArray();// console.log(serializeArray);//// })window.onload = function () {$("#btnId").click(function () {$.post("/login",$("#formId").serialize(),function(data){console.log($("#formId").serialize());if(data.success){alert("登录成功");}else{$("#tip").text(data.errorMsg)}})})}function changeCode(self) {// 原生JS// self.src = "/imagecode?time="+new Date();// self.setAttribute("src","/imagecode?time="+new Date());// AJAX// $(self).prop("src","/imagecode?time="+new Date());$(self).attr("src","/imagecode?time="+new Date());}
</script>
</html>