Introduction to kaptcha:
kaptcha is a very useful verification code generation tool. Since it has many configurable items, it can easily and quickly generate various verification codes.
Development tools and core technologies used:
1. eclipse
2. mybatis
3. Spring
4. springmvc
5. Kaptcha
This article will introduce two ways to use kaptcha:
Method 1: Configure in spring-kaptcha.xml
Method 2: Configure in web.xml
Officially begin:
1. Build a skeleton
1. Add dependencies:
<!-- Verification code--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
To use kaptcha verification code, except for spring and mybatis dependencies, just introduce this one.
2. Improve the configuration file
① spring-dao.xml
<!-- Configure the integration of mybatis process--> <!-- 1. Configure the properties of database-related parameters properties: ${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2. Configure the database connection pool--> <bean id="dataSource"> <!-- Configure the connection pool properties--> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- Private properties of c3p0 connection pool --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- Close the connection and does not commit automatically --> <property name="autoCommitOnClose" value="false"/> <!-- Get the connection timeout time-> <property name="checkoutTimeout" value="10000"/> <!-- Number of retries when the connection fails --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- Get the connection time-out time--> <property name="checkoutTimeout" value="10000"/> <!-- Number of retries when the connection fails --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- Get the connection time-out time--> <property name="checkoutTimeout" value="10000"/> <!-- Number of retries when the connection fails --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- 3. Configure mybatis' sqlSessionFactory --> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <!-- Automatic scan of mappers.xml file --> <property name="mapperLocations" value="classpath:mappers/*.xml"/> <!-- mybatis configuration file --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- Scan the entity package, use the alias --> <property name="typeAliasesPackage" value="com.zhu.kaptcha.entity"></property> </bean> <!-- 4. Spring will automatically find the class under the DAO interface--> <bean> <property name="basePackage" value="com.zhu.kaptcha.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean>②spring-service.xml
<!-- Scan all annotations in the service package --> <context:component-scan base-package="com.zhu.kaptcha.service"/> <!-- Transaction Management --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> <!-- Configure annotation-based declarative things --> <tx:annotation-driven transaction-manager="transactionManager"/>
③spring-web.xml
<!-- Configure springmvc --> <!-- 1. Turn on springMvc annotation mode --> <mvc:annotation-driven /> <!--2. Define view parser --> <bean id="viewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 3. Scan the web-related beans --> <context:component-scan base-package="com.zhu.kaptcha.controller"/>
④web.xml
<servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Encoding filter--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
At this point, the skeleton is built up and the database operation is completed.
2. Operation of database
1. Entity layer
User.java
public class User { private int uid; private String userName; private String password;}2. Dao Layer
UserDao.java
public interface UserDao { User findUserByUserName(String userName);}UserDao.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zhu.kaptcha.dao.UserDao"> <select id="findUserByUserName" resultType="com.zhu.kaptcha.entity.User"> SELECT * FROM tb_user WHERE user_name=#{userName} </select></mapper>3. Service layer
UserServiceImpl.java
@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public boolean login(String userName, String password) { User user = userDao.findUserByUserName(userName); if (passWord.equals(user.getPassWord())) { return true; } else { return false; } }}Note: When writing to the dao layer and service layer, you should do a Junit test. The test is relatively simple, so I won't explain it here.
3. Integrate kaptcha
Method 1: Configure through spring-kaptcha.xml
1. Create a new spring-kaptcha.xml configuration file in the spring folder of resources, with the following content:
spring-kaptcha.xml
<bean id="captchaProducer"> <property name="config"> <bean> <constructor-arg> <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">125</prop> <prop key="kaptcha.image.height">45</prop> <prop key="kaptcha.textproducer.font.size">45</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">Song font, Kaiyi, Microsoft Yahei</prop> </props> </constructor-arg> </bean> </property> </bean>
Note: This bean is configured with some verification code attributes, and can also be written directly in spring-web.xml. According to personal habits, I like to write the configuration of different modules in different files.
2. Create a new 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: The route of this controller is "kaptcha", so the src of the front-end verification code will be kaptcha.jpg.
3. Create a new tool class to compare verification codes
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: The parameter passed by get here is called "verifyCodeActual", so the name value of the verification code in the page should also be this.
Next, you can use the verification code!
4. Controller for user login
UserController.java
@Controller@RequestMapping("/user")public class UserController { @Autowired private UserService userService; @RequestMapping("/login") public String login(@RequestParam("userName") String userName, @RequestParam("passWord") String password, HttpServletRequest request) { boolean result = userService.login(userName, password); if (!CodeUtil.checkVerifyCode(request)) { request.setAttribute("codeErr", "Verification code is incorrect!"); return "fail"; } else { if (result) { request.setAttribute("user", userName); return "success"; } else { request.setAttribute("errMsg", "Error in username or password!"); return "fail"; } } }}Note: Here we call the CodeUtil tool to compare whether the entered verification code is correct.
5. Front-end page
login.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Login</title> <script type="text/javascript"> function refresh() { document.getElementById('captcha_img').src="kaptcha.jpg?"+Math.random(); } </script></head><body> <form action="${pageContext.request.contextPath }/user/login" method="post"> userName:<input type="text" name="userName" /><br /> password:<input type="password" name="passWord" /><br /> verification code: <input type="text" placeholder="Please enter verification code" name="verifyCodeActual"> <div> <img id="captcha_img" onclick="refresh()" src="kaptcha.jpg" /> </div> <input type="submit" value="Login" /> </form> </body></html>success.jsp
<body> <h1>Welcome to log in, ${user}</h1></body>fail.jsp
<body> Sorry, login failed, reason:<br> ${codeErr} <h2>${errMsg}</h2></body>Note: The js code of login.jsp is to complete the "click to change" function; note that the name of the verification code should be the same as the name passed in the tool class, and src is the controller route that generates the verification code plus .jpg.
6. Test:
Enter the correct verification code:
Login successfully:
Enter the wrong verification code:
The verification code is displayed incorrectly on the page:
Click the verification code to change it!
Method 2: Configure verification code in web.xml
Compared with method one, one increases and two decreases.
reduce:
1. Based on the above project, delete CodeController.java .
2. Delete spring-kaptcha.xml and retain the others.
increase:
1. Add the following configuration in web.xml :
<!-- Verification code--> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- Is there a border--> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <!-- Font color--> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>black</param-value> </init-param> <!-- Image width --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- Which characters to use to generate verification code--> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345679</param-value> </init-param> <!-- Image width --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- Font size --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- Interference line--> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>red</param-value> </init-param> <!-- Number of characters --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- Font--> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping>
Note: This configuration is used to configure the verification code. Note that the last <url-pattern>/kaptcha.jpg</url-pattern> should correspond to src = "kaptcha.jpg" in the verification code.
This completes the configuration of the verification code and then test it. test:
Enter the wrong verification code:
The page displays verification code error:
Enter the correct verification code:
Login successfully:
Test passed!
Summarize:
1. It is very simple to add verification code to the page, just add <img src= "xx"> . Use an img tag, and then point to the route of the controller that generates the verification code through src plus .jpg (the verification code is configured in spring), or point to the controller through src
<url-pattern>/kaptcha.jpg</url-pattern> , i.e. src="kaptcha.jpg" .
2. Clicking to replace is also simple, just add an onclick event to the img tag and then complete it with js.
Click to change js:
<script type="text/javascript"> function refresh() { document.getElementById('captcha_img').src="kaptcha.jpg?"+Math.random(); } </script> Then add onclick="refresh()" to the img tag, thus completing the click event.
3. More kaptcha attribute configuration
| Constant | describe | default value |
| kaptcha.border | Image border, legal value: yes, no | yes |
| kaptcha.border.color | Border color, legal value: r,g,b (and optional alpha) or white,black,blue. | black |
| kaptcha.border.thickness | Border thickness, legal value: >0 | 1 |
| kaptcha.image.width | Picture wide | 200 |
| kaptcha.image.height | High picture | 50 |
| kaptcha.producer.impl | Image implementation class | com.google.code.kaptcha.impl.DefaultKaptcha |
| kaptcha.textproducer.impl | Text implementation class | com.google.code.kaptcha.text.impl.DefaultTextCreator |
| kaptcha.textproducer.char.string | Text collection, verification code value is obtained from this collection | abcde2345678gfynmnpwx |
| kaptcha.textproducer.char.length | Verification code length | 5 |
| kaptcha.textproducer.font.names | Font | Arial, Courier |
| kaptcha.textproducer.font.size | Font size | 40px. |
| kaptcha.textproducer.font.color | Font color, legal values: r,g,b or white,black,blue. | black |
| kaptcha.textproducer.char.space | Text interval | 2 |
| kaptcha.noise.impl | Interference implementation class | com.google.code.kaptcha.impl.DefaultNoise |
| kaptcha.noise.color | Interference color, legal value: r,g,b or white,black,blue. | black |
| kaptcha.obscurificator.impl | Picture style: Water Ribbon com.google.code.kaptcha.impl.WaterRipple Fisheyecom.google.code.kaptcha.impl.FishEyeGimpy Shadowcom.google.code.kaptcha.impl.ShadowGimpy | com.google.code.kaptcha.impl.WaterRipple |
| kaptcha.background.impl | Background implementation class | com.google.code.kaptcha.impl.DefaultBackground |
| kaptcha.background.clear.from | Background color gradient, start color | light grey |
| kaptcha.background.clear.to | Background color gradient, end color | White |
| kaptcha.word.impl | Text Renderer | com.google.code.kaptcha.text.impl.DefaultWordRenderer |
| kaptcha.session.key | session key | KAPTCHA_SESSION_KEY |
| kaptcha.session.date | session date | KAPTCHA_SESSION_DATE |
The above content is a compilation of personal notes. If there are any errors, you are welcome to criticize and correct me!