Ajax + Struts2 implement verification code function instance code, ajaxstruts2
As we all know, verification codes are very common in our lives. Many companies are tossing a variety of verification codes. Here we use a simple example to implement the verification code function (ps: actually, I hate the verification code ).
Today we are sharing dynamic verification code input through ajax. Here we use ajax + struts2 for this verification. Create a web project. Then you need to import the corresponding struts package. Then we need to write a class to generate the verification code.
The name here is 01_image.jsp. The main function of this type is to generate a verification code, which contains various lines and random numbers. Here I set 5 numbers for verification, if you want to change it to another one, you can simply add a letter to the cycle in which the number is generated.
<% @ Page language = "java" pageEncoding = "UTF-8" %> <% @ page contentType = "image/jpeg" import = "java. awt. *, java. awt. image. *, java. util. *, javax. imageio. * "%> <%! Public Color getColor () {Random random = new Random (); int r = random. nextInt (256); // 0-255int g = random. nextInt (256); int B = random. nextInt (256); return new Color (r, g, B);} public String getNum () {String str = ""; Random random = new Random (); for (int I = 0; I <5; I ++) {str + = random. nextInt (10); // 0-9} return str ;}%> <% response. setHeader ("pragma", "no-cache"); response. setHeader ("cache-control", "no-cache"); response. setDateHeader ("expires", 0); BufferedImage image = new BufferedImage (80, 30, BufferedImage. TYPE_INT_RGB); Graphics g = image. getGraphics (); g. setColor (new Color (200,200,200); g. fillRect (0, 0, 80, 30); for (int I = 0; I <50; I ++) {Random random = new Random (); int x = random. nextInt (80); int y = random. nextInt (30); int xl = random. nextInt (x + 10); int yl = random. nextInt (y + 10); g. setColor (getColor (); g. drawLine (x, y, x + xl, y + yl);} g. setFont (new Font ("serif", Font. BOLD, 16); g. setColor (Color. BLACK); String checkNum = getNum (); // "2525" StringBuffer sb = new StringBuffer (); for (int I = 0; I <checkNum. length (); I ++) {sb. append (checkNum. charAt (I) + ""); // "2 5 2 5"} g. drawString (sb. toString (), 15, 20); session. setAttribute ("CHECKNUM", checkNum); // 2525 // output ImageIO through the byte output stream. write (image, "jpeg", response. getOutputStream (); out. clear (); out = pageContext. pushBody (); %>
Next, write the html page for entering the verification code. Here I am in a jsp file. Name it checkcode. jsp
<Th> Verification Code: </th> <td> <input type = "text" name = "checkcode" id = "checkcodeID" maxlength = "5"/> </td> </td> <td id = "resID"> </td> </tr> </table> </form>
Then add javascript code to this file. Here, of course, ajax is used. The ajax encoding steps have been described in detail, so we will use them directly here. Write the ajax. js file and put it under the js directory. Then find another checkcode. jsp file to introduce the content of the Chinese js file ajax. js:
// Create an AJAX asynchronous object, that is, XMLHttpRequestfunction createAJAX () {var ajax = null; try {ajax = new ActiveXObject ("microsoft. xmlhttp ");} catch (e1) {try {ajax = new XMLHttpRequest ();} catch (e2) {alert (" your browser does not support ajax, change the browser ") ;}} return ajax ;}
Then there is the js content in chenkcode.
// Remove the space function trim (str) {str = str. replace (/^ \ s */, ""); // remove str = str from the left. replace (/\ s * $/, ""); // from the right, remove all kgex return str;} document. getElementById ("checkcodeID "). onkeyup = function () {var checkcode = this. value; checkcode = trim (checkcode); if (checkcode. length = 5) {var ajax = createAJAX (); var method = "POST"; var url = "$ {pageContext. request. contextPath}/checkRequest? Time = "+ new Date (). getTime (); ajax. open (method, url); // set the ajax request header to post, which will automatically encode the requested Chinese Characters in UTF-8. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); var content = "checkcode =" + checkcode; ajax. send (content); ajax. onreadystatechange = function () {if (ajax. readyState = 4) {if (ajax. status = 200) {var tip = ajax. responseText; var img = document. createElement ("img"); img. src = tip; img. style. width = "14px"; img. style. height = "14px"; var td = document. getElementById ("resID"); td. innerHTML = ""; td. appendChild (img) ;}}} else {var td = document. getElementById ("resID"); td. innerHTML = "";}}
Then begin to write the server-side code. for verification, you need such a class:
Package cn. tf. checkcode; import java. io. IOException; import java. io. printWriter; import javax. servlet. http. httpServletResponse; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionContext; import com. opensymphony. xwork2.ActionSupport; // verification code check public class CheckcodeAction extends ActionSupport {private String checkcode; public void setCheckcode (String checkcode) {this. checkcode = checkcode;}/*** verify * @ throws IOException */public String check () throws IOException {// image path String tip = "images/a.jpg "; // obtain the verification code String checkcodeServer = (String) ActionContext from the server. getContext (). getSession (). get ("CHECKNUM"); if (checkcode. equals (checkcodeServer) {tip = "images/B .jpg";} // outputs the tip variable to the ajax asynchronous object in the form of an IO stream. HttpServletResponse response = ServletActionContext. getResponse (); response. setContentType ("text/html; charset = UTF-8"); PrintWriter pw = response. getWriter (); pw. write (tip); pw. flush (); pw. close (); return null ;}}
Finally, write the corresponding method in the struts. xml file.
<struts><package name="myPackage" extends="struts-default" namespace="/"> <action name="checkRequest" class="cn.tf.checkcode.CheckcodeAction" method="check"></action></package></struts>
The running result is as follows: if the verification succeeds, a green flag is returned, and a Red Cross is returned for an error.
The above is an example code of Ajax + Struts2 Code provided by Alibaba Cloud for verification. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!