When we do the verification code, it is often due to anti-cheating. Sometimes the verification is intentionally added to many interference factors. 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.
- In this example, a piece of JS is added based on the original authentication method, and the returned value is obtained through XMLHTTP to verify whether it is valid, even if the user's browser does not support JS, it will not affect his normal use.
- To prevent cheating, one piece is reloaded when the user connects to the wrong input three times. This will also help the user to fail to enter the correct image because the verification code on the image cannot be identified.
- 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 ).
- 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 the user experience, but also saves bandwidth costs slightly, but correspondingly adds a piece of JavaScript on the pageCodeToday, as the network speed is getting faster and people require convenient and comfortable, it seems that we should pay more attention to providing users with 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 entered successfully. 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 easily 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 ());
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1365651