1.添加依赖
<dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency>
2.添加配置
在config包下创建一个kaptcha配置类,配置验证码的一些生成属性。代码:
import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; @Configuration public class KaptchaConfig { @Bean public DefaultKaptcha producer() { Properties properties=new Properties(); properties.put("kaptercha.border", "no"); properties.put("kaptercha.textproducer.font.color", "black"); properties.put("kaptercha.textproducer.char.space", "5"); Config config=new Config(properties); DefaultKaptcha defaultKaptcha=new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
3.生成代码
新建一个控制器,提供系统登陆相关的api,在其中添加生成验证码接口。代码:
import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import com.louis.mango.common.utils.IOUtils; @RestController public class SysLoginController { @Autowired private Producer producer; @GetMapping("kaptcha.jpg") public void kaptcha(HttpServletResponse response,HttpServletRequest request) throws ServletException,IOException{ response.setHeader("Cache-Control", "no-store,no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text=producer.createText(); //生成图片验证码 BufferedImage image=producer.createImage(text); //保存验证码到session request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out=response.getOutputStream(); ImageIO.write(image, "jpg", out); //用到IO工具包控制开关 IOUtils.closeQuietly(out); } }
1