Preface:
Regarding the introduction of kaptcha and the integration of spring kaptcha, I have explained in detail in another article. Please refer to: spring kaptcha verification code.
This article will introduce two ways of integrating springboot into kaptcha.
Development tools and technologies:
1. Idea 2017
2. springboot 2.0.2
3. Kaptcha
Officially begin:
Method 1: Configure through kaptcha.xml
1. Create a new spring Initializr using idea
2. Add kaptcha dependencies:
<!-- kaptcha verification code--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
3. Create a new kaptcha.xml under resources, with the following content:
kaptcha.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Generate kaptcha bean--> <bean id="captchaProducer"> <property name="config"> <bean> <constructor-arg type="java.util.Properties"> <!--Set kaptcha properties--> <props> <prop key = "kaptcha.border ">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.image.width">100</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha. key="kaptcha.textproducer.font.size">27</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">Song font, Kai font, Microsoft Yahei</prop> <prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop> <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop> <prop key="kaptcha.noise.color">black</prop> <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop> <prop key="kaptcha.background.clear.from">185,56,213</prop> <prop key="kaptcha.background.clear.to">white</prop> <prop key="kaptcha.textproducer.char.space">3</prop> </props> </constructor-arg> </bean> </property> </bean></beans>
Note: The content in kaptcha.xml is actually the same as the content in spring-kaptcha.xml when spring integrates kaptcha. It means handing kaptcha to the spring container management, setting some properties, and then directly injecting when needed.
4. Load kaptcha.xml:
Add @ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}), add this annotation, springboot will load the kaptcha.xml file. Note that the path of kaptcha.xml should not be written incorrectly, the classpath is the resources directory here.
5. Write a controller to generate verification code:
CodeController.java
@Controllerpublic class CodeController { @Autowired private Producer captchaProducer = null; @RequestMapping("/kaptcha") public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); // Generate verification code String capText = captchaProducer.createText(); session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // Write BufferedImage to the client bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } }}Note: Inject the bean just configured in kaptcha.xml in this controller path, and then you can use it to generate the verification code and output the verification code to the client; remember the route of this class, the src of the verification code of the front-end page needs to point to this route.
6. Create a new verification code comparison tool:
CodeUtil.java
public class CodeUtil { /** * Convert the obtained front-end parameter to string type* @param request * @param key * @return */ public static String getString(HttpServletRequest request, String key) { try { String result = request.getParameter(key); if(result != null) { result = result.trim(); } if("".equals(result)) { result = null; } return result; }catch(Exception e) { return null; } } /** * Verification code verification* @param request * @return */ public static boolean checkVerifyCode(HttpServletRequest request) { //Get the generated verification code String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); //Get the verification code entered by the user String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual"); if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) { return false; } return true; }}Note: This class is used to compare the generated verification code with the verification code entered by the user. The generated verification code will be automatically added to the session, and the user input will be obtained through getParameter. Note that the key value of getParameter should be consistent with the name value of the verification code in the page.
7. Use verification code:
①Controller
HelloWorld.java
@RestControllerpublic class HelloWorld { @RequestMapping("/hello") public String hello(HttpServletRequest request) { if (!CodeUtil.checkVerifyCode(request)) { return "The verification code is incorrect!"; } else { return "hello,world"; } }} ②Page
hello.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> function refresh() { document.getElementById('captcha_img').src="/kaptcha?"+Math.random(); } </script></head><body><form action="/hello" method="post"> Verification code: <input type="text" placeholder="Please enter verification code" name="verifyCodeActual"> <div> <img id="captcha_img" onclick="refresh()" src="/kaptcha" /> </div> <input type="submit" value="submit" /></form></body></html>Note: The verification code is essentially a picture, so use the <img> tag, and then use src = "/kaptcha" to point to the route of the controller that generates the verification code; call the js code through onclick = "refresh()" to realize the click-to-switch function; pay attention to the value of the name in <input name = "verifyCodeActual">, and the key value passed in when obtaining the verification code entered by the user through the getParameter() method of request in CodeUtil should be consistent with the name value here.
8. Test:
Enter the correct verification code
Verification passed
Enter the wrong verification code
Verification failed
Method 2: Configure kaptcha through configuration class
1. Configure kaptcha
Compared with method one, one increases and two decreases.
reduce:
①Delete kaptcha.xml ②Delete @ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}) annotation on the startup class
increase:
① Create a new KaptchaConfig configuration class, the content is as follows:
KaptchaConfig.java
@Configurationpublic class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha(){ DefaultKaptcha captchaProducer = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "yes"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "blue"); properties.setProperty("kaptcha.image.width", "110"); properties.setProperty("kaptcha.image.height", "40"); properties.setProperty("kaptcha.textproducer.font.size", "30"); properties.setProperty("kaptcha.session.key", "code"); properties.setProperty("kaptcha.textproducer.char.length", "4"); properties.setProperty("kaptcha.textproducer.font.names", "Song font, Kai font, Microsoft Yahei"); Config config = new Config(properties); captchaProducer.setConfig(config); return captchaProducer; }}Note: This class is used to configure Kaptcha, which is equivalent to kaptcha.xml in Method 1. Add kaptcha to the IOC container, then return to an instance with the set properties, and finally inject it into the CodeController. You can use it to generate verification code in the CodeController. Pay special attention to return captchaProducer; the name of captchaProducer in private Producer captchaProducer = null;, otherwise the bean will not be loaded.
2. Test:
Enter the correct verification code:
Verification passed
Enter the wrong verification code
Verification failed
In order to explain that the verification codes of the two times are generated based on two methods, the verification codes of the first and second methods are set different attributes. From the picture, we can see that the colors, interference lines, backgrounds, etc. of the verification codes of the two times are different.
Summarize:
1. Process sorting:
No matter which way, you should first add kaptcha to the spring container, that is, there should be a kaptcha bean; then create a new controller, and inject the kaptcha bean into the controller to generate verification codes; then there is a tool class that compares the verification code, and call the tool class in the test controller for verification code comparison; finally, on the front-end page, you only need to use <img src = "/生成验证码的controller的路由"> to obtain the verification code. By adding a click event to this img tag, you can realize "click to switch verification code".
2. Comparison with spring integration kaptcha
Spring integration kaptcha also introduces two methods. The configuration is the simplest in web.xml, and there is no need to write a controller that generates verification code. In the page, use src to point to the <url-pattern> value of kaptcha's servlet in web.xml.
Both methods of springboot integrating kaptcha are similar to the second method of spring integrating kaptcha. They are used to configure beans first, and then use controllers to generate verification codes. The front-end uses src to point to this controller. The difference is that if the controller that generates verification codes is /xxx, then src = "xxx.jpg" when springboot integrating kaptcha, src = "/xxx"。
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.