JSP + Ajax Verification Code

Source: Internet
Author: User

 

1. When we do the verification code, we often resort to anti-cheating reasons, and sometimes we intentionally add many interference factors to the verification. At this time, the verification code is not clearly displayed and users often enter errors. In this way, not only do you need to refresh the page, so that the user does not read the Verification Code clearly, but does not modify it. If the session is not used to save other data entered by the user (such as the name ), the content that the user just entered does not exist, which leads to a poor user experience.

2. In this example, a piece of JS is added based on the original verification method, and the returned value is obtained through XMLHTTP to verify whether the result is valid, even if the user's browser does not support JS, it will not affect his normal use.

3. In order to prevent cheating, the user reloads one piece when three input errors are made. This will make it impossible for the user to enter the correct image because the verification code on the image cannot be identified.

4. This example is particularly suitable for verifying whether the user name is valid. You only need to make an SQL query from the background and return a value or XML. (There are too many such examples, so I will not go into details here ).

5. The advantage of this example is that it is very convenient for users to input and reduces requests to the server. It can be said that it not only improves user experience, but also saves bandwidth costs slightly, however, we need to add a piece of JavaScript code on the page accordingly. Today, as the network speed is getting faster and faster, and people demand convenience and comfort, it seems that we should pay more attention to providing users with a good experience.

The Code is as follows:

1. IMG. jsp, enter the home page

<% @ Page contenttype = "text/html; charset = GBK" Language = "Java"

Import = "Java. SQL. *" errorpage = "" pageencoding = "GBK" %>

<%

// Set Chinese char

// Cody by JarryLi@gmail.com;

// Homepage: jiarry.126.com

Request. setcharacterencoding ("GBK ");

Response. setcharacterencoding ("GBK ");

Response. setcontenttype ("text/html; charset = GBK ");

%>

<HTML>

<Head>

<Title> image verification </title>

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">

<SCRIPT src = "net. js"> </SCRIPT>

</Head>

<Body>

Ajax (prompt without refreshing) Verification Code instance! Cody by Jarry

<HR>

<%

String num = request. getparameter ("num ");

String random = (string) Session. getattribute ("random ");

String name = request. getparameter ("name ");

If (num! = NULL & random! = NULL & name! = NULL)

{

If (Num. Equals (random ))

{

Out. println ("<font style =/" color: green; font-weight: bold/">

Congratulations! The verification code is successfully entered. Here is the submission result page, which can be written to the database! </Font>

<A href =/"IMG. jsp/"> return and retest </a> <br> ");

Out. println ("Your name is:" + name );

Out. println ("<br> ");

Out. println ("You entered:" + num );

Out. println ("Verification Code:" + random );

Out. println ("</body> ");

Return; // javascript: history. Go (-1)

}

}

%>

<SCRIPT type = "text/JavaScript">

VaR times = 0;

Function subform (){

VaR gtext = This. Req. responsetext;

VaR info = Document. getelementbyid ("info ");

If (gtext. indexof ("validate_successful ")! =-1 ){

// Info. innerhtml = "<font color = green> Verification Code passed </font> ";

Document. Forms ["myform"]. Submit ();

// If the value is valid, the verification code passes.

} Else {

Times ++;

If (times> = 3) {// If the connection is incorrect three times, reload the image to prevent cheating and the user cannot see the image clearly;

Info. innerhtml = "three input errors in a row. Update the verification code. Enter ";

Document. Forms ["myform"]. Num. value = "";

Show (document. getelementbyid ('random '));

Times = 0;

} Else {

Info. innerhtml = "times +" Times verification code error. Please note that it is case sensitive ";

}

Document. Forms ["myform"]. Num. Select ();

}

}

Function validata (OBJ ){

VaR enter = true;

VaR info = Document. getelementbyid ("info ");

VaR MSG = "";

If (obj. Name. value. Match (/^/S * $/G) {// if no name is entered, a prompt is displayed.

MSG + = "enter your name <br>"; enter = false

}

If (obj. Num. value. Match (/^/S * $/G) {// if no verification code is entered, a prompt is displayed.

MSG + = "Enter the Verification Code <br>"; enter = false

}

If (enter = false ){

Info. innerhtml = MSG;

Return false;

}

VaR url = "num. jsp? Num = "+ obj. Num. value;

VaR newxmlhttp = new net. contentloader (URL, subform, "", "get", null, null );

Return false;

}

Function show (o ){

// Reload the verification code

VaR timenow = new date (). gettime ();

O. src = "random. jsp? D = "+ timenow;

/*

// Timeout execution;

SetTimeout (function (){

O. src = "random. jsp? D = "+ timenow;

}

, 20 );

*/

}

</SCRIPT>

<Form action = "IMG. jsp" name = "myform" method = "Post"

Onsubmit = "Return validata (this);">

Your name: <input type = "text" name = "name" size = 10> (to better illustrate this example, add a name) <br>

Verification Code: <input type = "text" name = "num" size = 10 maxlength = "4">

<A href = "javascript: Show (document. getelementbyid ('random ')"> The Verification Code cannot be viewed clearly </a> <br>

<Br> <input type = "Submit" value = "Submit"> <br>

<Div id = info style = "color: red; padding: 10px; font-size: 12px;"> </div>

</Form>

</Body>

</Html>

2. Num. jsp: feed back the page of the XMLHTTP request

<% @ Page contenttype = "text/html; charset = GBK" Language = "Java"

Import = "Java. SQL. *" errorpage = "" pageencoding = "GBK" %>

<%

// Set Chinese char

// Cody by JarryLi@gmail.com;

// Homepage: jiarry.126.com

Request. setcharacterencoding ("GBK ");

Response. setcharacterencoding ("GBK ");

Response. setcontenttype ("text/html; charset = GBK ");

%>

<%

String num = request. getparameter ("num ");

String random = (string) Session. getattribute ("random ");

If (num! = NULL & random! = NULL)

{

If (! Num. Equals (random ))

{

/*

Out. println ("<SCRIPT> alert ('verification code error! Please try again. ') </SCRIPT> ");

Out. println ("<SCRIPT> history. Go (-1) </SCRIPT> ");

// Response. sendredirect ("IMG. jsp ");

*/

Out. Print ("validate_failed:" + random );

}

Else

{

// Out. println ("<center> Verification Successful! </Center> ");

Out. Print ("validate_successful:" + random );

}

}

%>

3. Random. jsp: page for generating Verification Code Images

<% @ Page autoflush = "false" Import = "Java. util. *, java. AWT .*,

Java. AWT. image. *, com.sun.image.codec.jpeg. *, java. util. * "%>

<%

// Set Chinese char

// Cody by JarryLi@gmail.com;

// Homepage: jiarry.126.com

Request. setcharacterencoding ("GBK ");

Response. setcharacterencoding ("GBK ");

Response. setcontenttype ("text/html; charset = GBK ");

%>

<%

String chose = "0123456789 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ";

Char display [] = {'0', '', '0','', '0', '', '0 '}, ran [] = {'0', '0', '0', '0'}, temp;

Random Rand = new random ();

For (INT I = 0; I <4; I ++)

{

Temp = chose. charat (RAND. nextint (chose. Length ()));

Display [I * 2] = temp;

Ran [I] = temp;

}



String random = string. valueof (Display );

Session. setattribute ("random", String. valueof (RAN ));

%>

<%

Out. Clear ();

Response. setcontenttype ("image/JPEG ");

Response. addheader ("Pragma", "No-Cache ");

Response. addheader ("cache-control", "No-Cache ");

Response. adddateheader ("expries", 0 );

Int width = 80, Height = 30;

Bufferedimage image = new bufferedimage (width, height,

Bufferedimage. type_int_rgb );

Graphics G = image. getgraphics ();

// Fill in the background color below

G. setcolor (color. Green );

G. fillrect (0, 0, width, height );

// Set the font color

G. setcolor (color. Red );

Font font = new font ("Arial", Font. Plain, 20 );

G. setfont (font );

// G. drawstring (random, 5, 14 );

G. drawstring (random, 5, 20 );

G. Dispose ();

Servletoutputstream outstream = response. getoutputstream ();

Required imageencoder encoder = required codec. createjpegencoder (outstream );

Encoder. encode (image );

Outstream. Close ();

%>

4. net. js. The encapsulated XMLHTTP object can be conveniently called.

/* namespacing object */

var net=new Object();



net.READY_STATE_UNINITIALIZED=0;

net.READY_STATE_LOADING=1;

net.READY_STATE_LOADED=2;

net.READY_STATE_INTERACTIVE=3;

net.READY_STATE_COMPLETE=4;

/*--- content loader object for cross-browser requests ---*/

net.ContentLoader=function(url,on_load,on_error,method,params,contentType){

this.req=null;

this.on_load=on_load;

this.on_error=(on_error) ? on_error : this.defaultError;

this.loadXMLDoc(url,method,params,contentType);

}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){

if (!method)

{

method="GET";

}

if (!contentType && method=="POST")

{

contentType='application/x-www-form-urlencoded';

}

if (window.XMLHttpRequest)

{

this.req=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

//add try catch;

try {

this.req = new ActiveXObject("Msxml2.XMLHTTP");

}catch (e1){

try {

this.req = new ActiveXObject("Microsoft.XMLHTTP");    

} catch (e2){

}

}

//

//this.req=new ActiveXObject("Microsoft.XMLHTTP");

}

if (this.req)

{

try

{

var loader=this;

this.req.onreadystatechange=function()

{

net.ContentLoader.onReadyState.call(loader);

}

this.req.open(method,url,true);

if (contentType)

{

this.req.setRequestHeader('Content-Type', contentType);

}

this.req.send(params);

}

catch (err)

{

this.on_error.call(this);

}

}

}

net.ContentLoader.onReadyState=function(){

var req=this.req;

var ready=req.readyState;

if (ready==net.READY_STATE_COMPLETE){

var httpStatus=req.status;

if (httpStatus==200 || httpStatus==0){

this.on_load.call(this);

}else{

this.on_error.call(this);

}

}

}

net.ContentLoader.prototype.defaultError=function(){

alert("error fetching data!"

+"/n/nreadyState:"+this.req.readyState

+"/nstatus: "+this.req.status

+"/nheaders: "+this.req.getAllResponseHeaders());

}

 

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.