Java之验证码的实现
作者:互联网
相关Maven
<!-- 验证码依赖kaptcha --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
配置注入
import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); // 图片边框 properties.setProperty("kaptcha.border", "yes"); // 边框颜色 properties.setProperty("kaptcha.border.color", "105,179,90"); // 字体颜色 properties.setProperty("kaptcha.textproducer.font.color", "red"); // 图片宽 properties.setProperty("kaptcha.image.width", "120"); // 图片高 properties.setProperty("kaptcha.image.height", "50"); // 字体大小 properties.setProperty("kaptcha.textproducer.font.size", "30"); // session key properties.setProperty("kaptcha.session.key", "code"); // 验证码长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); // 字体 properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
controller层
@Slf4j @Controller public class LoginController { @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private DefaultKaptcha captchaProducer; @RequestMapping("/{url}") public String redirect(@PathVariable String url){ return url; } //登录功能 @RequestMapping("/loginIn") public String login(@RequestParam("username") String username, @RequestParam("password") String password, String vrifyCode, Model model, HttpSession session){ log.info("登录用户:" + username); log.info("登录密码:" + password); if(username.equals("")){ model.addAttribute("key","用户名不能为空"); return "login"; }else if(password.equals("")) { model.addAttribute("key", "密码不能为空"); return "login"; }else if(!session.getAttribute("vrifyCode").equals(vrifyCode)){ //判断验证码是否一致 model.addAttribute("key","验证码不正确"); return "login"; }else { User user = userService.loginIn(username); if(user != null){ if(passwordEncoder.matches(password,user.getPassword())){ log.info(username + "用户登录成功"); //登录成功则存入用户信息到session中 session.setAttribute("LoginUser",username); return "index"; }else { log.info(username + "用户密码错误"); model.addAttribute("key","用户密码错误"); return "login"; } }else { log.info("登录失败," + username + "用户不存在"); model.addAttribute("key","登录失败," + username + "用户不存在"); return "login"; } } } //获取验证码的请求路径 @RequestMapping("/kaptcha") public void getKaptchaImage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { //生产验证码字符串并保存到session中 String createText = captchaProducer.createText(); httpServletRequest.getSession().setAttribute("vrifyCode", createText); //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中 BufferedImage challenge = captchaProducer.createImage(createText); ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组 captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } }
前端页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>登录页面</title> <link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/> <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> <!--验证码刷新--> function refresh() { $("#captcha_img").attr("src", ""); $("#captcha_img").attr("src", "/kaptcha"); } </script> </head> <body> <form role="form" th:action="@{/loginIn}" method="post"> <div style="color: red"> <input type="hidden" name="_method" th:text="${key}" th:if="${key!=null}"/> </div> <p> 账号:<input type="text" id="username" name="username"> <br> </p> <p> 密码:<input type="password" id="password" name="password"> <br> </p> <label>验证码:</label> <input type="text" name="vrifyCode"><br> <img th:src="@{/kaptcha}" onclick="refresh()" alt="无法显示图片" title="点击换图" id="captcha_img"><br><br> <p style="float:left;"> <input type="submit" id="login" value ="登录"> </p> </form> <form role="form1" th:action="@{/regist}" method="post"> <p style="float:left;"><input type="submit" id="regist" value="注册"></p> </form> </body> </html>
页面展示
标签:username,Java,实现,kaptcha,验证码,setProperty,return,properties 来源: https://www.cnblogs.com/cjzzz/p/16256499.html