AJAX+STRUTS2 Implementation Verification Code verification function Instance Code _ajax related

Source: Internet
Author: User
Tags getcolor stringbuffer

As we all know, the verification code in our life are very common, many companies are tossing a variety of verification code, here briefly with a small case to achieve the function of the Verification code (PS: I really hate the verification code this thing).

Sharing today is the dynamic validation of validation code input via Ajax. What we're using here is ajax+struts2 to do this validation. We create a new Web project. Then you need to import the corresponding package for struts. Then we need to write a class to generate the Captcha.

This is named 01_image.jsp, this type of main function is to generate verification code, which is a variety of drawing lines, random numbers, and so on, I set up here is 5 digital verification, if you want to change to other also can, the general idea is in the generation of the number of the loop where the letter can be.

<%@ 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-255 int g = Random.nextint (256);
T 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 (a);//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 < i++) {Random Random = new Random (); int x = Random.nextint (); int y = Random.nextint (M);
T 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 stream via byte output imageio.write (image, "JPEG", Response.getoutputstream
());
Out.clear ();
out = Pagecontext.pushbody (); %>

Next, write the HTML page of the input verification code, I am here in a JSP file. Named checkcode.jsp

<th> Verification Code:</th>
<td><input type= "text" name= "Checkcode" id= "Checkcodeid" maxlength= "5"/> </td>
<td></td> <td id=
"Resid" ></td >
</tr> 
</table>
</form>

Then add the JavaScript code to the file, which is of course an AJAX, which is already written in detail before the Ajax coding steps, so we use it directly here. For Ajax.js after writing to the JS directory, and then find a checkcode.jsp in the introduction of Chinese JS file ajax.js content:

Creates an Ajax asynchronous object, that is, the XMLHttpRequest
function 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, please replace the browser")
;
}
return ajax;
}

Then it's the JS content in Chenkcode.

/Remove the space function trim (str) {str=str.replace (/^\s*/, "") on either side;//Remove the space from the left side Str=str.replace (/\s*$/, "");
Starting from the right, the K-song is removed from 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, it will automatically utf-8 the requested Chinese characters ajax.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= "";}} 

The

Then starts writing the server-side code, and the validation requires a class like this:

 package cn.tf.checkcode; import java.io.IOException; import java.io.PrintWriter; Import J
Avax.servlet.http.HttpServletResponse;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionContext;
Import Com.opensymphony.xwork2.ActionSupport; Verify code Check public class Checkcodeaction extends actionsupport{private string checkcode, public void Setcheckcode (String chec Kcode) {This.checkcode = Checkcode}/** * validation * @throws ioexception/public String check () throws IOException {//Picture road
Diameter String tip= "images/a.jpg";
Gets the authentication code String checkcodeserver= (String) Actioncontext.getcontext () from the server (). GetSession (). Get ("Checknum"); if (Checkcode.equals (Checkcodeserver)) {tip= "images/b.jpg"}///IO Stream output The tip variable to an Ajax asynchronous object 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, the appropriate method is written 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 results of the operation are as follows: The validation succeeds returns a green tick, and the wrong Red fork.

The above is a small series to introduce the AJAX+STRUTS2 to implement the verification code verification Function Example code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.