转载:https://blog.csdn.net/dayonglove2018/article/details/106612549
import com.wf.captcha.SpecCaptcha;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;@RestController@RequestMapping("/book/code")public class CaptchaController2 {/*** 生成验证码* @return* @throws Exception*/@GetMapping("/getCode")public void getCode(HttpServletResponse response) throws Exception {ServletOutputStream outputStream = response.getOutputStream();//算术验证码 数字加减乘除. 建议2位运算就行:captcha.setLen(2);
// ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);// 中文验证码
// ChineseCaptcha captcha = new ChineseCaptcha(120, 40);// 英文与数字验证码SpecCaptcha captcha = new SpecCaptcha(120, 40);//英文与数字动态验证码
// GifCaptcha captcha = new GifCaptcha(120, 40);// 中文动态验证码
// ChineseGifCaptcha captcha = new ChineseGifCaptcha(120, 40);// 几位数运算,默认是两位captcha.setLen(6);// 获取运算的结果String result = captcha.text();System.out.println(result);captcha.out(outputStream);}}
前端页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>Title</title><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<form action="/book/login" method="post">昵称:<input type="text" name="username" id="username"><br/>密码:<input type="text" name="password" id="password"><br/>验证码:<input type="text" name="captcha" placeholder="验证码"><img src="/book/code/getCode" id="captchaImg" onclick="verifyCode()" title="点击刷新"><input type="submit" value="提交">
</form>
<script>function verifyCode(){$("#captchaImg").attr("src","code/getCode?"+Math.random());}
</script></body>
</html>
服务器端打印效果: