Jquery provides a simple example of refreshing verification codes.
1. Ideas:
The verification code image on the page is servlet, and jquery is used for asynchronous verification of information.
2. Files used
VerifyCodeServlet. java -- servlet used to generate images
ResultServlet. java -- servlet used to verify the correctness of the Verification Code
VerifyCode. js-verify the js File
Jquery. js -- source file in the jquery package
VerifyCode. jsp -- page
3. Code
VerifyCodeServlet. java
Java code
Import java. awt. color; import java. awt. font; import java. awt. graphics2D; import java. awt. image. bufferedImage; import java. util. random; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. ht Tp. HttpSession; public class VerifyCodeServlet extends HttpServlet {// The width of the Verification Code image. Private int width = 60; // height of the Verification Code image. Private int height = 20; // number of characters in the verification code private int codeCount = 4; private int x = 0; // font height private int fontHeight; private int codeY; char [] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'h ', 'I', 'J', 'k', 'l', 'M', 'n', 'O', 'P', 'Q', 'R ', 'S ', 't', 'U', 'V', 'w', 'x', 'y', 'z', '0', '1 ', '2', '3', '4', '5', '6', '7', '8', '9 '}; /*** initialize and verify image attributes */public void init () throws ServletException {// From the web. get the initial information in xml // width String strWidth = this. getInitParameter ("width"); // height String strHeight = this. getInitParameter ("height"); // Number of Characters String strCodeCount = this. getInitParameter ("codeCount"); // convert the configuration information to a value. try {if (strWidth! = Null & strWidth. length ()! = 0) {width = Integer. parseInt (strWidth);} if (strHeight! = Null & strHeight. length ()! = 0) {height = Integer. parseInt (strHeight);} if (strCodeCount! = Null & strCodeCount. length ()! = 0) {codeCount = Integer. parseInt (strCodeCount) ;}} catch (NumberFormatException e) {}x = width/(codeCount + 1); fontHeight = height-2; codeY = height-4 ;} protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, java. io. IOException {// define the image buffer BufferedImage buffImg = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); Graphics2D g = BuffImg. createGraphics (); // create a Random number generator class random Random = new Random (); // fill the image in white g. setColor (Color. WHITE); g. fillRect (0, 0, width, height); // create a font. The font size depends on the Image height. Font font = new Font ("Fixedsys", Font. PLAIN, fontHeight); // set the Font. G. setFont (font); // draw a border. G. setColor (Color. BLACK); g. drawRect (0, 0, width-1, height-1); // generates 160 random interference lines, making it difficult for other programs to detect the authentication code in the image. G. setColor (Color. BLACK); for (int I = 0; I <160; I ++) {int x = random. nextInt (width); int y = random. nextInt (height); int xl = random. nextInt (12); int yl = random. nextInt (12); g. drawLine (x, y, x + xl, y + yl);} // randomCode is used to save the randomly generated Verification Code, so that the user can perform verification after logon. StringBuffer randomCode = new StringBuffer (); int red = 0, green = 0, blue = 0; // a random codeCount verification code is generated. For (int I = 0; I <codeCount; I ++) {// obtain the randomly generated verification code number. String strRand = String. valueOf (codeSequence [random. nextInt (36)]); // generate a random color component to construct the color value, so that the color value of each output number will be different. Red = random. nextInt (255); green = random. nextInt (255); blue = random. nextInt (255); // draw the verification code into the image with a random color. G. setColor (new Color (red, green, blue); g. drawString (strRand, (I + 1) * x, codeY); // combine the four random numbers. RandomCode. append (strRand);} // Save the four-digit verification code to the Session. HttpSession session = req. getSession (); session. setAttribute ("validateCode", randomCode. toString (); // disable image caching. Resp. setHeader ("Pragma", "no-cache"); resp. setHeader ("Cache-Control", "no-cache"); resp. setDateHeader ("Expires", 0); resp. setContentType ("image/jpeg"); // output the image to the Servlet output stream. ServletOutputStream sos = resp. getOutputStream (); ImageIO. write (buffImg, "jpeg", sos); sos. close () ;}import java. awt. color; import java. awt. font; import java. awt. graphics2D; import java. awt. image. bufferedImage; import java. util. random; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServlet; import javax. servlet. Http. HttpServletRequest; import javax. servlet. http. HttpServletResponse; import javax. servlet. http. HttpSession; public class VerifyCodeServlet extends HttpServlet {// The width of the Verification Code image. Private int width = 60; // height of the Verification Code image. Private int height = 20; // number of characters in the verification code private int codeCount = 4; private int x = 0; // font height private int fontHeight; private int codeY; char [] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'h ', 'I', 'J', 'k', 'l', 'M', 'n', 'O', 'P', 'Q', 'R ', 'S ', 't', 'U', 'V', 'w', 'x', 'y', 'z', '0', '1 ', '2', '3', '4', '5', '6', '7', '8', '9 '}; /*** initialize and verify image attributes */public void init () throws ServletException {// From the web. get the initial information in xml // width String strWidth = this. getInitParameter ("width"); // height String strHeight = this. getInitParameter ("height"); // Number of Characters String strCodeCount = this. getInitParameter ("codeCount"); // convert the configuration information to a value. try {if (strWidth! = Null & strWidth. length ()! = 0) {width = Integer. parseInt (strWidth);} if (strHeight! = Null & strHeight. length ()! = 0) {height = Integer. parseInt (strHeight);} if (strCodeCount! = Null & strCodeCount. length ()! = 0) {codeCount = Integer. parseInt (strCodeCount) ;}} catch (NumberFormatException e) {}x = width/(codeCount + 1); fontHeight = height-2; codeY = height-4 ;} protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, java. io. IOException {// define the image buffer BufferedImage buffImg = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); Graphics2D g = BuffImg. createGraphics (); // create a Random number generator class random Random = new Random (); // fill the image in white g. setColor (Color. WHITE); g. fillRect (0, 0, width, height); // create a font. The font size depends on the Image height. Font font = new Font ("Fixedsys", Font. PLAIN, fontHeight); // set the Font. G. setFont (font); // draw a border. G. setColor (Color. BLACK); g. drawRect (0, 0, width-1, height-1); // generates 160 random interference lines, making it difficult for other programs to detect the authentication code in the image. G. setColor (Color. BLACK); for (int I = 0; I <160; I ++) {int x = random. nextInt (width); int y = random. nextInt (height); int xl = random. nextInt (12); int yl = random. nextInt (12); g. drawLine (x, y, x + xl, y + yl);} // randomCode is used to save the randomly generated Verification Code, so that the user can perform verification after logon. StringBuffer randomCode = new StringBuffer (); int red = 0, green = 0, blue = 0; // a random codeCount verification code is generated. For (int I = 0; I <codeCount; I ++) {// obtain the randomly generated verification code number. String strRand = String. valueOf (codeSequence [random. nextInt (36)]); // generate a random color component to construct the color value, so that the color value of each output number will be different. Red = random. nextInt (255); green = random. nextInt (255); blue = random. nextInt (255); // draw the verification code into the image with a random color. G. setColor (new Color (red, green, blue); g. drawString (strRand, (I + 1) * x, codeY); // combine the four random numbers. RandomCode. append (strRand);} // Save the four-digit verification code to the Session. HttpSession session = req. getSession (); session. setAttribute ("validateCode", randomCode. toString (); // disable image caching. Resp. setHeader ("Pragma", "no-cache"); resp. setHeader ("Cache-Control", "no-cache"); resp. setDateHeader ("Expires", 0); resp. setContentType ("image/jpeg"); // output the image to the Servlet output stream. ServletOutputStream sos = resp. getOutputStream (); ImageIO. write (buffImg, "jpeg", sos); sos. close ();}}
ResultServlet. java
Java code
Import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class ResultServlet extends HttpServlet {/*** 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 {doPost (request, response);}/*** 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 {response. setContentType ("text/html; charset = UTF-8"); String validateC = (String) request. getSession (). getAttribute ("validateCode"); String veryCode = request. getParameter ("c"); PrintWriter out = response. getWriter (); if (veryCode = null | "". equals (veryCode) {out. println ("Verification code is empty");} else {if (validateC. equals (veryCode) {out. println ("correct Verification Code");} else {out. println ("Verification code error") ;}} out. flush (); out. close () ;}import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class ResultServlet extends HttpServlet {/*** 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 {doPost (request, response);}/*** 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 {response. setContentType ("text/html; charset = UTF-8"); String validateC = (String) request. getSession (). getAttribute ("validateCode"); String veryCode = request. getParameter ("c"); PrintWriter out = response. getWriter (); if (veryCode = null | "". equals (veryCode) {out. println ("Verification code is empty");} else {if (validateC. equals (veryCode) {out. println ("correct Verification Code");} else {out. println ("Verification code error") ;}} out. flush (); out. close ();}}
VerifyCode. js
Js Code
Function changeImg () {var imgSrc =$ ("# imgObj"); var src = imgSrc. attr ("src"); imgSrc. attr ("src", chgUrl (src);} // timestamp // do not allow the browser to read the cache in order to make the image generated each time inconsistent, therefore, you need to add the timestamp function chgUrl (url) {var timestamp = (new Date ()). valueOf (); url = url. substring (0, 17); if (url. indexOf ("&")> = 0) {url = url + "× tamp =" + timestamp;} else {url = url + "? Timestamp = "+ timestamp;} return url;} function isRightCode () {var code = $ (" # veryCode "). attr ("value"); code = "c =" + code; $. ajax ({type: "POST", url: "resultServlet", data: code, success: callback});} function callback (data) {$ ("# info" ).html (data);} function changeImg () {var imgSrc =$ ("# imgObj"); var src = imgSrc. attr ("src"); imgSrc. attr ("src", chgUrl (src);} // timestamp // in order to make the generated image inconsistent each time, the browser is not allowed to read the cache. Timestamp function chgUrl (url) {var timestamp = (new Date ()). valueOf (); url = url. substring (0, 17); if (url. indexOf ("&")> = 0) {url = url + "× tamp =" + timestamp;} else {url = url + "? Timestamp = "+ timestamp;} return url;} function isRightCode () {var code = $ (" # veryCode "). attr ("value"); code = "c =" + code; $. ajax ({type: "POST", url: "resultServlet", data: code, success: callback});} function callback (data) {$ ("# info" ).html (data );}
VerifyCode. jsp
Html code
<% @ Page language = "java" 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">
The simple example of jquery's implementation of the brushless newest verification code above is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for helping customers.