Getting Started with Ajax instances

Source: Internet
Author: User
Tags object final functions gettext string version tostring stringbuffer
Ajax

  First, straight to the point

These times, the blind can see, Ajax is striding towards us. Whether we are advocating or opposing, or ignoring, Ajax like a trend, the seats turned to all of us.

As for the definition of Ajax or the big talk, someone has published a voluminous text online, and I don't want to be scripted here.

Just want to say that I feel some of the advantages, for the wrong, you can also discuss with me:

The first is asynchronous interaction, the user does not feel the submission of the page, and certainly does not wait for the page to return. This is the first feeling of using AJAX technology to give users a page.

The second is the fast response, which is also a strong user experience.

Then it is related to our developers, the successful processing of complex UI, we have been in B/S mode UI is not as rich as the C/S model UI. Now because of the large number of Ajax use of JS, the design of complex UI has become more successful.

Finally, the return object of the AJAX request is an XML file, which is also a trend, the same as the Web service trend. Easy to combine with Web service.

Well, gossip less, let's go to the point.

Our first example is a Web application based on a servlet for the background.

  Second, servlet-based Ajax

This is a very common UI, when the user selects Zhejiang in the first selection box, the second selection box appears in the Zhejiang City, and when the user selects Jiangsu in the first selection box, the Jiangsu City appears in the second selection box.

First, let's look at the configuration file Web.xml and configure a servlet inside, as usual:

<web-app version= "2.4"
Xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">

<servlet>
<servlet-name>SelectCityServlet</servlet-name>
<servlet-class>com.stephen.servlet.SelectCityServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SelectCityServlet</servlet-name>
<url-pattern>/servlet/SelectCityServlet</url-pattern>
</servlet-mapping>

</web-app>

Then, look at our JSP file:

&lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" &gt;


&lt;html&gt;


&lt;head&gt;


&lt;title&gt;MyHtml.html&lt;/title&gt;


 


&lt;meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" &gt;


&lt;meta http-equiv= "description" content= "This are my page" &gt;


 


&lt;!--&lt;link rel= "stylesheet" type= "Text/css" href= "./styles.css" &gt;--&gt;


 


&lt;/head&gt;


&lt;script type= "Text/javascript" &gt;


function GetResult (stateval) {


var url = "Servlet/selectcityservlet?state=" +stateval;


if (window. XMLHttpRequest) {


req = new XMLHttpRequest ();


}else if (window. ActiveXObject) {


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


  }


if (req) {


Req.open ("Get", url, True);


Req.onreadystatechange = complete;


req.send (NULL);


  }


 }


function Complete () {


if (req.readystate = = 4) {


if (req.status = = 200) {


var city = req.responseXML.getElementsByTagName ("city");


File://alert (city.length);


var str=new Array ();


for (Var i=0;i&lt;city.length;i++) {


Str[i]=city[i].firstchild.data;


}


File://alert (document.getElementById ("City"));


Buildselect (Str,document.getelementbyid ("City"));


  }


  }


 }


function Buildselect (str,sel) {


sel.options.length=0;


for (Var i=0;i&lt;str.length;i++) {


Sel.options[sel.options.length]=new Option (Str[i],str[i])


  }


 }


&lt;/script&gt;


&lt;body&gt;


&lt;select name= "state" &gt;


&lt;option value= "" &gt;Select&lt;/option&gt;&gt;


&lt;option value= "ZJ" &gt;ZEHJIANG&lt;/option&gt;&gt;


&lt;option value= "ZS" &gt;JIANGSU&lt;/option&gt;&gt;


&lt;/select&gt;


&lt;select id= "City" &gt;


&lt;option value= "" &gt;CITY&lt;/option&gt;


&lt;/select&gt;


&lt;/body&gt;


&lt;/html&gt;

At first glance, it's no different from our usual JSP. Take a closer look, different in JS inside.

Let's first look at the first method: GetResult (Stateval), in which the first is to obtain the XMLHttpRequest, and then the Url:req.open ("Get", url, true) of the request is set; Next, set the Receive method for the request return value: Req.onreadystatechange = complete; The return value is--complete (), and finally the request is sent: Req.send (null);

And then we'll look at our return value Reception method: Complete (), which, in this method, first determines whether it returns correctly, and, if it returns correctly, parses the returned XML file with the DOM. For the use of DOM, this is no longer a story, please refer to the documentation. After the value of the city is obtained, the Buildselect (Str,sel) method is assigned to the corresponding selection box.

Finally, let's look at the servlet file:

import java.io.IOException;


import Java.io.PrintWriter;


 


import javax.servlet.ServletException;


import Javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import Javax.servlet.http.HttpServletResponse;


 


 /**


* @author Administrator


  *


* TODO To change the template for this generated type comment go to


* Window-preferences-java-code Style-code Templates


  */


public class Selectcityservlet extends HttpServlet {


 


 


public Selectcityservlet () {


super ();


  }


 


public void Destroy () {


Super.destroy ();


  }


 


public void doget (HttpServletRequest request, httpservletresponse response)


throws Servletexception, IOException {


Response.setcontenttype ("Text/xml");


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


String state = request.getparameter (' state ');


stringbuffer sb=new stringbuffer ("&lt;state&gt;");


if ("ZJ". Equals (state)) {


sb.append ("&lt;city&gt;hangzhou&lt;/city&gt;&lt;city&gt;huzhou&lt;/city&gt;");


} else if ("Zs". Equals (state)) {


sb.append ("&lt;city&gt;nanjing&lt;/city&gt;&lt;city&gt;yangzhou&lt;/city&gt;&lt;city&gt;suzhou&lt; /city&gt; ");


}


sb.append ("&lt;/state&gt;");


PrintWriter out=response.getwriter ();


Out.write (sb.tostring ());


Out.close ();


  }


 }

This class is also very simple, first of all, take the state parameter from the request, then generate the corresponding XML file according to the state parameter, and finally output the XML file to the PrintWriter object.

Until now, the first example of the code has all ended. Is it easier? Let's go to the second instance! This is an application of Ajax based on JSP.

  Three, JSP-based Ajax

This example is about the input checksum, we know that when applying for a user, we need to go to the database to confirm the uniqueness of the user, and then we can continue to apply.

This verification requires access to the background database, but does not want users to submit after the wait, of course, is the Ajax technology.

First look at the JSP that displays the UI:

&lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" &gt;


&lt;html&gt;


&lt;head&gt;


&lt;title&gt;Check.html&lt;/title&gt;


 


&lt;meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" &gt;


&lt;meta http-equiv= "description" content= "This are my page" &gt;


 


&lt;!--&lt;link rel= "stylesheet" type= "Text/css" href= "./styles.css" &gt;--&gt;


 


&lt;/head&gt;


&lt;script type= "Text/javascript" &gt;


var http_request = false;


function send_request (URL) {//Initialize, specify handler functions, send request functions


http_request = false;


file://starts initializing the XMLHttpRequest object


if (window. XMLHttpRequest) {File://Mozilla browser


http_request = new XMLHttpRequest ();


if (http_request.overridemimetype) {//Set MIME category


Http_request.overridemimetype (' Text/xml ');


  }


   }


else if (window. ActiveXObject) {//IE browser


try {


http_request = new ActiveXObject ("Msxml2.xmlhttp");


} catch (e) {


try {


http_request = new ActiveXObject ("Microsoft.XMLHTTP");


} catch (e) {}


  }


   }


if (!http_request) {//exception, failed to create object instance


Window.alert ("Cannot create XMLHttpRequest object instance.");


return false;


   }


http_request.onreadystatechange = ProcessRequest;


//Determines the way and URL to send the request and whether to execute the next code synchronously


Http_request.open ("Get", url, True);


http_request.send (NULL);


  }


//processing functions for return information


function ProcessRequest () {


if (http_request.readystate = = 4) {//Judge object state


if (http_request.status = = 200) {//information has been successfully returned to begin processing information


alert (http_request.responsetext);


} else {file://page is not normal


alert ("The page you requested has an exception.) ");


  }


  }


  }


function Usercheck () {


var f = document.form1;


var username = f.username.value;


if (username== "") {


Window.alert ("The user name can not be null!");


F.username.focus ();


return false;


   }


else {


send_request (' check1.jsp?username= ' +username);


   }


  }


 


&lt;/script&gt;


&lt;body&gt;


&lt;form name= "Form1" action= "" method= "post" &gt;


User name:&lt;input type= "text" name= "username" "value=" "&gt;


&lt;input type= "button" name= "Check" value= "Check" &gt;


&lt;input type= "Submit" name= "submit" value= "Submit" &gt;


&lt;/form&gt;


&lt;/body&gt;


&lt;/html&gt;

All JS is the same as the previous example, the difference is only the operation of the return value, this time with alert to display: alert (http_request.responsetext);

Let's look at processing logical JSPs:

<%@ page contenttype= "text/html; charset=gb2312 "language=" java "errorpage=" "%>
<%
String username= request.getparameter ("username");
if ("Educhina". Equals (username)) Out.print ("User name is already registered, replace a user name.") ");
else Out.print ("User name has not been used, you can continue.") ");
%>

Very simple, get the parameters first, then do the processing, and finally print the results in out.
Our third example still takes this unique checksum as an example, this time combining the struts development framework to complete the development of Ajax.

  Four, the Ajax based on struts

First, we still configure the Struts application and still configure it in the Struts-config,xml file, as follows:

<action type= "Com.ajax.CheckAction"
Scope= "Request" path= "/ajax/check" >
<forward name= "Success" path= "/check.jsp"/>
</action>


Just like the usual struts application configuration, there is no actionform configuration.

Here is the action class:

 package Com.ajax;
 
 import java.io.PrintWriter;
&NBSP
 import javax.servlet.http.HttpServletRequest;
 import Javax.servlet.http.HttpServletResponse;
 
 import org.apache.struts.action.Action;
 import Org.apache.struts.action.ActionForm;
 import Org.apache.struts.action.ActionForward;
 import org.apache.struts.action.ActionMapping;
 import Org.apache.struts.action.DynaActionForm;
 
 /**
  * @author Administrator
  *
  * TODO to change the template for this Gen erated type comment Go to
  * Window-preferences-java-code style-code Templates
  */
 publ IC class Checkaction extends Action
 {
  Public final Actionforward execute (actionmapping mapping, Actionform form,
          httpservletrequest request,
           httpservletresponse response)
   throws Exception
   {
System.out.println (" Haha ..... .....................
String username= request.getparameter ("username");
System.out.println (username);
String Retn;
if ("Educhina". Equals (username)) Retn = "Can" t use the same name and the old Use,pls Select a difference ... ";
Else Retn = "Congraducation!you can use this name ...";
PrintWriter out=response.getwriter ();
          Out.write (RETN);
          out.close ();
Return Mapping.findforward ("Success");
  }
  public static void main (string[] args)
  {
 }
 

We can see that the logic inside is the same as in the servlet in the previous example. Finally, let's look at the JSP:

&lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" &gt;


&lt;html&gt;


&lt;head&gt;


&lt;title&gt;Check.html&lt;/title&gt;


 


&lt;meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" &gt;


&lt;meta http-equiv= "description" content= "This are my page" &gt;


 


&lt;!--&lt;link rel= "stylesheet" type= "Text/css" href= "./styles.css" &gt;--&gt;


 


&lt;/head&gt;


&lt;script type= "Text/javascript" &gt;


var http_request = false;


function send_request (URL) {//Initialize, specify handler functions, send request functions


http_request = false;


file://starts initializing the XMLHttpRequest object


if (window. XMLHttpRequest) {File://Mozilla browser


http_request = new XMLHttpRequest ();


if (http_request.overridemimetype) {//Set MIME category


http_request.overridemimetype (' text/xml ');


  }


   }


else if (window. ActiveXObject) {//IE browser


try {


http_request = new ActiveXObject ("Msxml2.xmlhttp");


} catch (e) {


try {


http_request = new ActiveXObject ("Microsoft.XMLHTTP");


} catch (e) {}


  }


   }


if (!http_request) {//exception, failed to create object instance


Window.alert ("Cannot create XMLHttpRequest object instance.");


return false;


   }


http_request.onreadystatechange = ProcessRequest;


//Determines the way and URL to send the request and whether to execute the next code synchronously


Http_request.open ("Get", url, True);


http_request.send (NULL);


  }


//Processing function of return information


function ProcessRequest () {


if (http_request.readystate = = 4) {//Judge object state


if (http_request.status = = 200) {//information has been successfully returned to begin processing information


alert (http_request.responsetext);


} else {file://page is not normal


alert ("The page you requested has an exception.) ");


  }


  }


  }


function Usercheck () {


var f = document.forms[0];


var username = f.username.value;


if (username== "") {


Window.alert ("The user name can not be null!");


F.username.focus ();


return false;


   }


else {


send_request (' ajax/check.do?username= ' +username);


   }


  }


 


&lt;/script&gt;


&lt;body&gt;


&lt;form name= "Form1" action= "" method= "post" &gt;


User name:&lt;input type= "text" name= "username" "value=" "&gt;


&lt;input type= "button" name= "Check" value= "Check" &gt;


&lt;input type= "Submit" name= "submit" value= "Submit" &gt;


&lt;/form&gt;


&lt;/body&gt;


&lt;/html&gt;

We can see that the JSP is basically the same, except to send the Url:ajax/check.do?username= ' +username.

Finally, let's look at a complex example based on struts and Ajax, and the UI code would be very complex without Ajax technology.

  How far a complex example

This is a more complex cascade: A total of eight list boxes, three Drop-down boxes. When you select from the first list box to the second list box, the option in the first selection box is the selection of the second list box; then, after selecting the first selection box, some options associated with the selected value appear in the Third list box. From the Third list box, select the option to the fourth list box, similarly, the option of the second selection box is also the option for the fourth list box; If you select the second selection box, some options associated with the Select value appear in the Sixth list box, and so on ...

The logic of this UI is more complex, but using Ajax makes it a lot simpler for us to implement, and this example uses the Pojo class and the business class in addition to the action class, and then we can connect it through the business class and the database.

Let's look at the configuration file first:

<action type= "Com.ajax.SelectAction"
Scope= "Request" path= "/ajax/select" >
<forward name= "Success" path= "/select.jsp"/>
</action>

Then look at the action class:

 /*


 /**


* title:base Dict Class


* Description:here Description is the function of class, here maybe Multirows


* Copyright:copyright (c) 2004


* @company freeborders Co., Ltd.


* @Goal Feng


* @Version 1.0


  */


 


package Com.ajax;


 


import Java.io.PrintWriter;


import java.util.List;


 


import javax.servlet.http.HttpServletRequest;


import Javax.servlet.http.HttpServletResponse;


 


import org.apache.struts.action.Action;


import Org.apache.struts.action.ActionForm;


import Org.apache.struts.action.ActionForward;


import org.apache.struts.action.ActionMapping;


 


 /**


* @author Administrator


  *


* TODO to change the template of this generated type comment go to


* Window-preferences-java-code Style-code Templates


  */


public class SelectAction extends Action


 {


Public Final Actionforward execute (actionmapping mapping, actionform form,


httpservletrequest Request,


httpservletresponse Response)


throws Exception


   {


Response.setcontenttype ("Text/xml");


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


String type = Request.getparameter ("type");


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


SYSTEM.OUT.PRINTLN (ID);


stringbuffer sb=new stringbuffer ("&lt;select&gt;");


sb.append ("&lt;type&gt;" +type+ "&lt;/type&gt;");


  


list = new Selectbusiness (). GetData (ID);


for (int i=0;i&lt;list.size (); i++)


  {


selectform sel = (selectform) list.get (i);


sb.append ("&lt;text&gt;" +sel.gettext () + "&lt;/text&gt;&lt;value&gt;" +sel.getvalue () + "&lt;/value&gt;");


  }


 


sb.append ("&lt;/select&gt;");


PrintWriter Out=response.getwriter ();


Out.write (sb.tostring ());


Out.close ();


System.out.println (sb.tostring ());


return Mapping.findforward ("Success");


   }


public static void Main (string[] args)


  {


  }


 }


 


Pojo class and business class:


package Com.ajax;


 /**


* @author Administrator


  *


* TODO To change the template for this generated type comment go to


* Window-preferences-java-code Style-code Templates


  */


public class Selectform


 {


private String text;


private String value;


 


  /**


* @return Returns the text.


   */


public String getText ()


  {


return text;


  }


  /**


* @param text the text to set.


   */


public void SetText (String text)


  {


this.text = text;


  }


  /**


* @return Returns the value.


   */


public String getValue ()


  {


return value;


  }


  /**


* @param value the value to set.


   */


public void SetValue (String value)


  {


this.value = value;


  }


public static void Main (string[] args)


  {


  }


 }


 


 


package Com.ajax;


 


import java.util.ArrayList;


import java.util.List;


 


 /**


* @author Administrator


  *


* TODO To change the template for this generated type comment go to


* Window-preferences-java-code Style-code Templates


  */


public class Selectbusiness


 {


public List getData (String ID)


  {


ArrayList list = new ArrayList ();


for (int i=1;i&lt;6;i++)


   {


selectform form = new Selectform ();


Form.settext (id+i);


Form.setvalue (id+i);


list.add (form);


   }


return list;


  }


 


public static void Main (string[] args)


  {


  }


 }

Next page







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.