1.springboot整合hutool-captcha生成验证码,首先是添加依赖 :
cn.hutool
hutool-captcha
${hutool-captcha.version}
2.生成并显示验证码
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import ltd.newbee.mall.common.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
@Controller
public class CommonController {
@GetMapping("/common/kaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/png");
ShearCaptcha shearCaptcha= CaptchaUtil.createShearCaptcha(150, 30, 4, 2);
// 验证码存入session
httpServletRequest.getSession().setAttribute("verifyCode", shearCaptcha);
// 输出图片流
shearCaptcha.write(httpServletResponse.getOutputStream());
}
@GetMapping("/common/mall/kaptcha")
public void mallKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/png");
ShearCaptcha shearCaptcha= CaptchaUtil.createShearCaptcha(110, 40, 4, 2);
// 验证码存入session
httpServletRequest.getSession().setAttribute(Constants.MALL_VERIFY_CODE_KEY, shearCaptcha);
// 输出图片流
shearCaptcha.write(httpServletResponse.getOutputStream());
}
}
3.前端逻辑实现
..