cn.hutool hutool-all 5.4.3
- package com.logincode;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- @SpringBootApplication
- public class LoginCodeApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(LoginCodeApplication .class, args);
- }
-
- }
# 应用服务 WEB 访问端口 server.port=8989
- package com.logincode.web;
-
- import cn.hutool.captcha.CaptchaUtil;
- import cn.hutool.captcha.CircleCaptcha;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
-
-
- @RestController
- @RequestMapping("/user")
- public class LoginCode {
-
- @Autowired
- private HttpServletResponse response;
-
- @Autowired
- private HttpSession session;
-
- /**
- * 功能:生成验证码
- *
- */
- @GetMapping("/code")
- void getCode() throws IOException {
- // 利用hutool工具,生成验证码图片资源
- CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 5);
- // 获得生成的验证码字符串
- String code = captcha.getCode();
- // 利用session来存储 验证码
- session.setAttribute("code", code);
- //将验证码图片的二进制数据响应体中response
- captcha.write(response.getOutputStream());
- }
-
- }
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>用户登入界面title>
- head>
- <body>
- 登入界面
- <form action="#" method="post">
- 用户username:<input type="text" name="username"><br/>
- 密码password:<input type="password" name="password"><br/>
- 验证码code:<input type="code" name="code"><br/>
- <img src="/user/code" id="code" onclick="refresh()">
- <br/>
- <input type="submit" value="登入/注册">
- <br/>
- form>
- <a href="/logout.do">退 出a>
- body>
- <script>
- function refresh() {
- document.getElementById("code").src = "/user/code?time" + new Date().getTime();
- }
- script>
- html>