Java Development --- verification code, java --- Verification Code

Source: Internet
Author: User

Java Development --- verification code, java --- Verification Code

Verification Code: prevents malicious password cracking, ticket swiping, Forum bumping, and page swiping.

This effectively prevents hackers from constantly trying to log on to a specific registered user using brute force cracking of specific programs. In fact, using the verification code is a method that many websites are currently using (such as China Merchants Bank's personal online banking, baidu community), we implemented this function in a relatively simple way. Although login is a little troublesome, this function is still necessary and important for the security of passwords of netizens. However, we still remind everyone to protect their passwords and try to use 6 or more passwords that contain numbers, letters, and symbols, do not use a simple password such as 1234 or a password similar to the user name, so that your account may be stolen and it may cause unnecessary trouble.

The verification code usually consists of some lines and some irregular characters. It is mainly used to prevent some hackers from stealing passwords.

For most websites, You need to click the verification code to fill in the box. Then, the verification code image is displayed. Click the red text next to the Verification code to change it.

Because the verification code is randomly generated, there is a high probability that the verification code image cannot be clearly identified, so note that the general website will have corresponding prompts, such as "cannot see clearly, if there is no prompt, click the current verification code image to complete the verification code replacement.

The following uses Jsp + Servle + JavaBean to implement the verification code:

Directly run the Code:

RandomValidateCode.java
Package com. oumyye. util;/** Author: oumyye */import java. awt. color; import java. awt. font; import java. awt. graphics; import java. awt. image. bufferedImage; import java. util. random; import javax. imageio. imageIO; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; public class RandomValidateCode {public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY"; // key private Random random = new Random (); private String randString = "0123456789 Random "; // randomly generated string private int width = 120; // picture width private int height = 40; // picture height private int lineSize = 40; // Number of interfering lines private int stringNum = 6; // Number of randomly generated characters/** obtain the Font */private Font getFont () {return new Font ("Fixedsys", Font. CENTER_BASELINE, 20);}/** obtain Color */private Color getRandColor (int fc, int bc) {if (fc> 255) fc = 255; if (bc> 255) bc = 255; int r = fc + random. nextInt (bc-fc-16); int g = fc + random. nextInt (bc-fc-14); int B = fc + random. nextInt (bc-fc-18); return new Color (r, g, B);}/*** generate random image */public void getRandcode (HttpServletRequest request, HttpServletResponse response) {HttpSession session = request. getSession (); // The BufferedImage class is an Image class with a buffer. The Image class is a class used to describe image information. BufferedImage Image = new BufferedImage (width, height, BufferedImage. TYPE_INT_BGR); Graphics g = image. getGraphics (); // generate the Graphics object of the Image object. You can perform various painting operations on the Image by modifying the object. fillRect (0, 0, width, height); g. setFont (new Font ("Times New Roman", Font. ROMAN_BASELINE, 20); g. setColor (getRandColor (100,133); // draw the interference line for (int I = 0; I <= lineSize; I ++) {drowLine (g );} // draw a random String randomString = ""; for (int I = 1; I <= stringNum; I ++) {randomString = drowString (g, randomString, I );} session. removeAttribute (RANDOMCODEKEY); session. setAttribute (RANDOMCODEKEY, randomString); System. out. println (randomString); g. dispose (); try {ImageIO. write (image, "JPEG", response. getOutputStream (); // outputs the images in the memory to the client in the form of flow} catch (Exception e) {e. printStackTrace () ;}/ ** draw String */private String drowString (Graphics g, String randomString, int I) {g. setFont (getFont (); g. setColor (new Color (random. nextInt (101), random. nextInt (111), random. nextInt (121); String rand = String. valueOf (getRandomString (random. nextInt (randString. length (); randomString + = rand; g. translate (random. nextInt (3), random. nextInt (3); g. drawString (rand, 13 * I, 30); return randomString;}/** draw interference line */private void drowLine (Graphics g) {int x = random. nextInt (width); int y = random. nextInt (height); int xl = random. nextInt (10); int yl = random. nextInt (15); g. drawLine (x, y, x + xl, y + yl);}/** get random characters */public String getRandomString (int num) {return String. valueOf (randString. charAt (num ));}}
ImageServlet .java
Package com. oumyye. servlet;/*** Author: oumyye */import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import com. oumyye. util. randomValidateCode; public class ImageServlet extends HttpServlet {/*** Constructor of the object. */public ImageServlet () {super () ;}/ *** Destruction of the servlet. <br> */public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setContentType ("image/jpeg"); // set the corresponding type to notify the browser that the output content is image response. setHeader ("Pragma", "No-cache"); // sets the response header to tell the browser not to cache the response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expire", 0); RandomValidateCode randomValidateCode = new RandomValidateCode (); try {randomValidateCode. getRandcode (request, response); // method of output image} catch (Exception e) {e. printStackTrace () ;}}/*** The doPost method of the servlet. <br> ** This method is called when a form has its tag value method equals to post. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {doGet (request, response);}/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occurs */public void init () throws ServletException {// Put your code here }}

Configuration File web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <display-name>0001web</display-name>   <servlet>    <description>ImageCreate</description>    <display-name>ImageCreate</display-name>    <servlet-name>ImageServlet</servlet-name>    <servlet-class>com.oumyye.servlet.ImageServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ImageServlet</servlet-name>    <url-pattern>/servlet/ImageServlet</url-pattern>  </servlet-mapping></web-app>

Index. jsp

<! DOCTYPE html> 

The interface is as follows:

Click images to refresh

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.