How to add a verification code to the login and registration page and refresh it in real time

Why add a verification code?
In order to prevent repeated submission of forms, putting pressure on the server

Tools needed: kaptcha-2.3.2.jar idea2019.3
Google verification code encapsulated servlet class

First import the jar package

After the import is complete, you can configure it directly in web.xml

The configuration code is as follows:

	<servlet>
		<servlet-name>KaptchaServlet</servlet-name>
		<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>KaptchaServlet</servlet-name>
		<url-pattern>/kaptcha.jpg</url-pattern>
	</servlet-mapping>
	

If you add and redeploy after the addition is complete, you will get a verification code picture after direct access
. The effect is shown in the figure;

Insert picture description here

The problem is coming?

How to get the characters inside after getting the picture

The tool will set up a session in the login background or registration background, and the value value can be retrieved through the id


        // 获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

Where KAPTCHA_SESSION_KEY is a constant fixed ID

The principle is that when we request the server and get the value through the session, we immediately delete the session to prepare for the next request.

This prevents multiple requests

Then get the sent verification code for comparison.
After correct, proceed to the next step. Incorrectly return to the page and echo the error message

String code = req.getParameter("code");
        //检查验证码有否有问题
        if (token != null && token.equalsIgnoreCase(code)) {
    
    
}else{
    
    

}

How to display the captcha image in the jsp page

Use img src attribute

                   <img  id="img_check" src="kaptcha.jpg" width="80px" height="40px" >

The src puts the address of the request servlet to get the picture

Guess you like

Origin blog.csdn.net/weixin_46999174/article/details/108771891