Jsp page Verification Code demo and jsp Verification Code demo
The ImageIO that generates the verification code on the java background is displayed on the front-end page. At the same time, the value of the verification code is passed into the session for matching with the verification code entered by the user. ajax technology is used in user verification, verify the verification code without refreshing the new page.
Program structure:
The VerifyCodeUtils program mainly contains the image that generates the verification code through java and the value of the verification code. The program is as follows:
Package utils; import java. awt. color; import java. awt. font; import java. awt. graphics2D; import java. awt. image. bufferedImage; import java. util. hashMap; import java. util. map; import java. util. random; public class VerifyCodeUtils {private static BufferedImage image = null; private static Random random = new Random (); // in your own defined number, generate four random numbers public static String getVerifyCode () {String str = ""; char [] code = ne W char [] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'h ', 'I', 'J', 'k', 'l', 'M', 'n', 'P', 'Q', 'R','s ', 'T', 'U', 'V', 'w', 'x', 'y', 'z', 'A', 'B', 'C ', 'D', 'E', 'F', 'G', 'h', 'I', 'J', 'k', 'M', 'n ', 'P', 'Q', 'R','s ', 't', 'U', 'V', 'w', 'x', 'y ', 'Z', '2', '3', '4', '5', '6', '7', '8', '9 '}; random random = new Random (); for (int I = 0; I <4; I ++) {str + = String. valueOf (code [random. nextInt (code. length)]);} return str;} // generate the verification code image public static Ma P getVerifyCode (int width, int heigth) {VerifyCodeUtils. image = new BufferedImage (width, heigth, BufferedImage. TYPE_INT_RGB); Graphics2D g = (Graphics2D) VerifyCodeUtils. image. getGraphics (); String verifyCode = getVerifyCode (); Map map = new HashMap (); map. put ("verifyCode", verifyCode); // fill the image with white g. setColor (Color. WHITE); g. fillRect (0, 0, width, heigth); // set the font g. setFont (new Font ("", Font. BOLD + Font. ITALIC, heigth-10); // draw the border. G. setColor (VerifyCodeUtils. getColor (); g. drawRect (0, 0, width, heigth); // randomly generates interference lines, making it difficult for other programs to detect the ID code in the image. setColor (Color. BLACK); for (int I = 0; I <50; I ++) {int x = VerifyCodeUtils. random. nextInt (width); int y = VerifyCodeUtils. random. nextInt (heigth); int xl = VerifyCodeUtils. random. nextInt (5); int yl = VerifyCodeUtils. random. nextInt (5); g. setColor (getColor (); g. drawLine (x, y, x + xl, y + yl );} Char c; for (int I = 0; I <4; I ++) {c = verifyCode. charAt (I); g. drawString (c + "", I * 20 + 40, heigth-10);} map. put ("image", VerifyCodeUtils. image); return map;} // randomization Color public static Color getColor () {int red = 0, green = 0, blue = 0; // generate a random color component to construct the color value, so that the color values of each output number are different. Red = VerifyCodeUtils. random. nextInt (255); green = VerifyCodeUtils. random. nextInt (255); blue = VerifyCodeUtils. random. nextInt (255); return new Color (red, green, blue );}}
VerifyCodeServlet transmits the verification code image generated by VerifyCodeUtils to the front end through io. The Code is as follows:
Package Servlet; import java. awt. image. bufferedImage; import java. io. IOException; import java. util. map; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import utils. verifyCodeUtils;/*** Servlet implementation class VerifyCodeServlet */@ WebServlet ("/") public class VerifyCodeServlet extends HttpServlet {private static final long serialVersionUID = 1L; /*** @ see HttpServlet # HttpServlet () */public VerifyCodeServlet () {super (); // TODO Auto-generated constructor stub}/*** @ see HttpServlet # doGet (HttpServletRequest request, response) */protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {response. setHeader ("Expires", "-1"); response. setHeader ("Cache-Control", "no-cache"); response. setHeader ("Pragma", "no-cache"); response. setHeader ("Content-type", "image/jpeg"); Map map = VerifyCodeUtils. getVerifyCode (223, 50); // pass the verifyCode value into the session to verify whether the verification code entered by the user is correct. getSession (). setAttribute ("verifyCode", map. get ("verifyCode "). toString (). toUpperCase (); // input the image IO to the front end through IO. write (BufferedImage) map. get ("image"), "jpg", response. getOutputStream ();}/*** @ see HttpServlet # doPost (HttpServletRequest request, response) */protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet (request, response );}}
The jsp code of the page is as follows:
<% @ 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 "> <Html>
The ajax code for js implementation is as follows:
/*****/Function check_verifyCode () {var XMLHttpReqVerifyCode = null; var url = document. getElementById ("base "). href + "/servlet/TestVerifyCodeServlet"; var verifyCode = document. getElementById ("verifyCode "). value; var tip = document. getElementById ("tip"); var errorTip = "The entered verification code is incorrect"; var successTip = "The entered verification code is correct"; tip. innerHTML = errorTip; if (verifyCode = null | verifyCode = "") {tip. innerHTML = errorTip; tip. style. color = "red";} else {if (window. XMLHttpRequest) {// XMLHttpReqVerifyCode = new XMLHttpRequest ();} else if (window. activeXObject) {// create an array var MSXML = ['msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; for (var I = 0; I <MSXML. length; I ++) {try {XMLHttpReqVerifyCode = new ActiveXObject (MSXML [I]);} catch (e) {}} XMLHttpReqVerifyCode. open ("POST", url, true); XMLHttpReqVerifyCode. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); XMLHttpReqVerifyCode. onreadystatechange = function testVerifyCodeServletResponse () {if (XMLHttpReqVerifyCode. readyState = 4 & (XMLHttpReqVerifyCode. status = 200 | XMLHttpReqVerifyCode. status = 304) {if (XMLHttpReqVerifyCode. responseText = 1) {tip. innerHTML = successTip; tip. style. color = "green";} else if (XMLHttpReqVerifyCode. responseText = 0) {tip. innerHTML = errorTip; tip. style. color = "red" ;}} XMLHttpReqVerifyCode. send ("code =" + verifyCode);} // interaction function createXMLHttpRequest (XMLHttpReq) {if (window. XMLHttpRequest) {// DOM2 browser XMLHttpReq = new XMLHttpRequest ();} else if (window. activeXObject) {// create an array var MSXML = ['msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; for (var I = 0; I <MSXML. length; I ++) {try {XMLHttpReq = new ActiveXObject (MSXML [I]);} catch (e) {}} return XMLHttpReq ;}}}
The interaction code between TestVerifyCodeServlet and js is:
Package Servlet; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** Servlet implementation class TestVerifyCodeServlet */@ WebServlet ("/TestVerifyCodeServlet") public class TestVerifyCo DeServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @ see HttpServlet # HttpServlet () */public TestVerifyCodeServlet () {super (); // TODO Auto-generated constructor stub}/*** @ see HttpServlet # doGet (HttpServletRequest request, response) */protected void doGet (HttpServletRequest request, response) throws ServletException, I OException {// TODO Auto-generated method stub String codeTrue = (String) request. getSession (). getAttribute ("verifyCode"); String codeInput = request. getParameter ("code"); System. out. println (codeInput); response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); // print the stream if (codeInput! = Null) {if (codeInput. toUpperCase (). equals (codeTrue) {out. println ("1");} else {out. println ("0") ;}}/ *** @ see HttpServlet # doPost (HttpServletRequest request, HttpServletResponse response) */protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet (request, response );}}
The xml code is
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <welcome-file-list> <welcome-file>demo.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>Servlet.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>TestVerifyCodeServlet</servlet-name> <servlet-class>Servlet.TestVerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestVerifyCodeServlet</servlet-name> <url-pattern>/servlet/TestVerifyCodeServlet</url-pattern> </servlet-mapping></web-app>
Result:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.