import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.code.kaptcha.Producer;
@Controller
public class UserHandler {
@Autowired
private Producer kaptcha;
@GetMapping("/validcode")
public void getKaptcha(HttpServletResponse response,HttpSession session) {
//生成验证码字符串和图片
String code = kaptcha.createText();
BufferedImage image = kaptcha.createImage(code);
//保存到session
session.setAttribute("code", code);
try {
//响应图片到浏览器
response.setContentType("image/png");
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
配合该文件
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
Properties properties = new Properties();
properties.setProperty(“kaptcha.image.width”, “100”);
properties.setProperty(“kaptcha.image.height”, “40”);
properties.setProperty(“kaptcha.textproducer.font.size”, “32”);
properties.setProperty(“kaptcha.textproducer.font.color”, “0,0,0”);
properties.setProperty(“kaptcha.textproducer.char.string”, “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ”);
properties.setProperty(“kaptcha.textproducer.char.length”, “4”);
properties.setProperty(“kaptcha.noise.impl”, “com.google.code.kaptcha.impl.NoNoise”);
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}