Java programmer from Stupid Bird to rookie (75) Struts2 (14) Struts2+ajax implementation of asynchronous verification __java

Source: Internet
Author: User

Due to the teacher's need to decorate the job, when adding an administrator, to verify that the user name of the administrator added is already present in the database, then the client gives the user a hint. The first thing I thought of was using Ajax to implement asynchronous verification techniques, because of the use of the SSH framework, so in this to the STRUTS2 and Ajax integration, because I have not yet summed up some of the knowledge of Ajax, so do not mention in this, the details of Ajax will be written in the future blog. Now we're going to do this with the Add admin, verify that the administrator's username exists. For this struts2+ajax implement asynchronous authentication technology.

First, let's take a look at our form form:

<td>
username
</td>
<td>
<input type= "text" name= "Admin.username" value=
"" Onblur= "Checkusername (This, ' adminaction!exists ')"/>
</td>
<td>
<span id= " Namemessage "style=" color:red; " ></span>
</td>
</tr>
<tr bgcolor= "#d6fdd0" >
<td>
password
</td>
<td>
<input type= "password" name= "Admin.password" value= ""/>
</td >
<td>
<span></span>
</td>
</tr>


We can see that when the text field of our username registers a onblur event, we let him execute the Checkusername method when the user name is missing the focus of the text field, OK, let's take a look at how our JS is implemented Ajax:

<script type= "Text/javascript" > var xmlhttprequest = null; Declares an empty object to receive the XMLHttpRequest Object function checkusername (field, url) {var uername = Field.value; if (uername = "" | | Uername.length < 3) {document.getElementById ("Namemessage"). InnerHTML = "username should be no less than 3 bits"; return;} else {if window. ActiveXObject)//IE browser {xmlhttprequest = new ActiveXObject ("Microsoft.XMLHTTP");} else if (window. XMLHttpRequest)///other browsers other than IE to implement {XMLHttpRequest = new XMLHttpRequest ();} if (null!= XMLHttpRequest) {//When accessing server-side with Get method Parameters, directly after "Ajaxservlet" plus parameters, the following send method is parameter null can be, with the Post method this must be in the Send parameter, as follows Xmlhttprequest.open ("Get", url
+ "? Admin.username=" +uername, true);
The callback function associated with Ajax is Xmlhttprequest.onreadystatechange = Ajaxcallback; To actually send data to the server//post, you must add the following line, and the Get method does not have to add this sentence Xmlhttprequest.setrequestheader ("Content-type", "application/
X-www-form-urlencoded ");
Xmlhttprequest.send (NULL); }} function Ajaxcallback () {//ajax A request will change the state four times, so we do it at the fourth time (that is, the end of a request) OK, if (XMLHttpRequest. readyState = = 4) {//Request success if (Xmlhttprequest.status = =) {var responsetext = Xmlhttprequest.responsetext; document.ge
Telementbyid ("Namemessage"). InnerHTML = ResponseText; }} </script>


Through the above comments I think we should be able to understand some of the content, we first go to verify that the content is empty, if it is empty to give users a hint. If you are not empty, judge the current browser, and then set the XMLHttpRequest object according to the browser, what is the XMLHttpRequest object? The XMLHttpRequest object is used to exchange data with the server in the background, and his main role:

· To update a Web page without reloading the page

· Request data from the server after the page has been loaded

· Receive data from the server after the page has been loaded

· Sending data to the server in the background


XMLHttpRequest is the most core object of Ajax, and it has several important methods or properties:
Open (): Creates a new request to the server.

Send (): Sends a request to the server.

Abort (): Exits the current request.

ReadyState: Provides the ready state of the current HTML.

ResponseText: The request response text returned by the server.


Where the XMLHttpRequest object's open () method has the following five parameters:

Request-type: The type of request sent. A typical value is a get or POST, but a head request can also be sent.

URL: The URL to connect to.

Asynch: True if you want to use an asynchronous connection, false otherwise. The parameter is optional and the default is true.

Username: If authentication is required, you can specify the user name here. The optional parameter has no default value.

Password: If authentication is required, you can specify a password here. The optional parameter has no default value.


The first three parameters are usually used. In fact, you should specify that the third argument is "true" even if an asynchronous connection is required. This is the default value, but it is easier to understand whether the request is asynchronous or synchronous.

After we get the XMLHttpRequest object, we use this object to execute our request in the background, and we must pay attention to our callback function when executing our request: Xmlhttprequest.onreadystatechange = The name of the callback function here can be ajaxcallback, not fixed dead. We can see that the above program request is sent to the adminaction in the Exists method, OK, let's go to the action method inside to see:

Public String exists () throws exception{
System.out.println (admin==null);
Boolean boo=dao.exists (Admin.getusername ());
  Gets the original PrintWriter object in order to output the response result without jumping to an attempt to    
        httpservletresponse response = Servletactioncontext.getresponse ();    
        Sets the character set    
        response.setcharacterencoding ("UTF-8");    
        PrintWriter out = Response.getwriter ();    
if (boo) {	     
        //directly enter the content of the response    
        out.println ("* User name already exists *");    
        /** formatted output time **/   
        Out.flush ();    
        Out.close ();    
}
OUT.PRINTLN ("* User name available *"); 
return null;
}


Students familiar with Ajax see this code should be very clear. Here is the main use of printwriter to our background information output to our front desk, here I do not explain in detail. OK, here we are, our asynchronous validation using STRUTS2+AJAX implementations. The following are the specific implementation effects:



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.