Getting started with Ajax + servlet instances

Source: Internet
Author: User

 

About the advantages of Ajax,

The first is Asynchronous interaction. The user does not feel the Page Submission and does not wait for the page to return. This is the first experience that users feel when using Ajax pages.

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

 

Then we are related to our developers. The successful processing of complex UIS has always worried that the UI in B/S mode is not as rich as the UI in C/S mode. Now, due to the extensive use of js in Ajax, the complex UI design has become more successful.

Finally, the returned objects of Ajax requests are XML files, which is also a trend, that is, the Web service trend. It is easy to combine with Web Services.

 

The first example is a Web application based on servlet.

 

  Servlet-based Ajax

This is a common UI. When you select Zhejiang in the first selection box, Zhejiang city appears in the second selection box. When you select Jiangsu in the first selection box, the second option box shows the city of Jiangsu.

First, let's look at the configuration file web. xml and configure a servlet in it, 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, let's look at our JSP file:

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> myhtml.html </title>

<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "Description" content = "this is my page">

<! -- <LINK rel = "stylesheet" type = "text/CSS" href = "./styles.css"> -->

</Head>
<SCRIPT type = "text/JavaScript">
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 <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 <Str. length; I ++ ){
Sel. Options [SEL. Options. Length] = New Option (STR [I], STR [I])
}
}
</SCRIPT>
<Body>
<Select name = "state" onchange = "getresult (this. Value)">
<Option value = ""> select </option>
<Option value = "ZJ"> zehjiang </option>
<Option value = "Zs"> Jiangsu </option>
</SELECT>
<Select id = "city">
<Option value = ""> city </option>
</SELECT>
</Body>
</Html>

At first glance, it seems like our common JSP. Take a closer look at the differences in Js.

First, let's look at the first method: getresult (stateval). In this method, first we get XMLHttpRequest; then we set the request URL: req. open ("get", URL, true); then set the Receiving Method of the request return value: req. onreadystatechange = complete; the method for receiving the returned value is -- complete (); the last is to send the request: req. send (null );

Then let's take a look at our method for receiving the returned value: complete (). In this method, we first determine whether the returned value is correct. If the returned value is correct, we use Dom to parse the returned XML file. The usage of Dom is not described here. Please refer to the relevant documents. After obtaining the value of city, you can use the buildselect (STR, Sel) method to assign values to the corresponding selection box.

Finally, let's take a 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
* 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 ("<State> ");
If ("ZJ". Equals (State )){
SB. append ("<city> Hangzhou </city> <city> Huzhou </city> ");
} Else if ("Zs". Equals (State )){
SB. append ("<city> Nanjing </city> <city> Yangzhou </city> <city> Suzhou </city> ");
}
SB. append ("</State> ");
Printwriter out = response. getwriter ();
Out. Write (sb. tostring ());
Out. Close ();
}
}

This class is also very simple. First, get the state parameter from the request, then generate the corresponding XML file based on the state parameter, and finally output the XML file to the printwriter object.

So far, the code in the first example has all ended. Is it relatively simple?

 

 

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.