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>
Transferred from: ITU tutorial network [www.baiyuncom]
Http://www.etoow.com/html/2007-05/1178781098.html
</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 = "/blog/"> 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? Let's go to the second instance! This is an Ajax Application Based on JSP.
Iii. jsp-based Ajax
This example is about Input Validation. We know that when applying for a user, you must go to the database to confirm the uniqueness of the user before continuing to apply.
This verification requires access to the back-end database, but does not require users to wait after submitting it here. Of course, it is time for Ajax technology to show its strength.
First, let's look at the JSP that displays the UI:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> check.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">
VaR http_request = false;
Function send_request (URL) {// initialize, specify the processing function, and send the request Function
Http_request = false;
File: // start initializing the XMLHTTPRequest object
If (window. XMLHttpRequest ){File: // MozillaBrowser
Http_request = new XMLHttpRequest ();
If (http_request.overridemimetype) {// sets the 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 ){}
Transferred from: ITU tutorial network [www.baiyuncom]
Http://www.etoow.com/html/2007-05/1178781098-2.html
}
}
If (! Http_request) {// exception. An error occurred while creating the object instance.
Window. Alert ("the XMLHTTPRequest object instance cannot be created .");
Return false;
}
Http_request.onreadystatechange = processrequest;
// Determine the request sending method and URL and whether to execute the following code synchronously
Http_request.open ("get", URL, true );
Http_request.send (null );
}
// Function for processing the returned information
Function processrequest (){
If (http_request.readystate = 4) {// judge the object status
If (http_request.status = 200) {// The information has been returned successfully. Start to process the information.
Alert (http_request.responsetext );
} Else {file: // The page is abnormal.
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 );
}
}
</SCRIPT>
<Body>
<Form name = "form1" Action = "" method = "Post">
User name: <input type = "text" name = "username" value = "> & nbsp;
<Input type = "button" name = "check" value = "check" onclick = "usercheck ()">
<Input type = "Submit" name = "Submit" value = "Submit">
</Form>
</Body>
</Html>
All JS files are the same as the previous example. The difference is that they only operate on the returned values. This time, alert is used to display: Alert (http_request.responsetext );
Let's look at the processing logic JSP:
<% @ Page contenttype = "text/html; charset = gb2312" Language = "Java" errorpage = "" %>
<%
String username = request. getparameter ("username ");
If ("educhina". Equals (username) Out. Print ("the user name has been registered. Please change to another user name. ");
Else Out. Print ("the user name has not been used. You can continue. ");
%>
It is very simple. first obtain the parameter, then process it, and finally print the result in the out.
In our third example, we still use this uniqueness verification as an example. This time we combined the struts development framework to complete Ajax development.
4. Struts-based Ajax
First, we will still configure the struts application, or in the Struts-config and XML files, as shown below:
<Action type = "com. Ajax. checkaction"
Scope = "request" Path = "/ajax/check">
<Forward name = "success" Path = "/check. jsp"/>
</Action>
The configuration is the same as that of a common struts application, but there is no actionform configuration.
The following is the action class:
Package com. Ajax;
Import java. Io. printwriter;
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 generated type comment go
* Window-preferences-Java-code style-code templates
*/
Public 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 with 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 the logic in servlet in the example. Finally, let's take a look at JSP:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> check.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">
VaR http_request = false;
Function send_request (URL) {// initialize, specify the processing function, and send the request Function
Http_request = false;
File: // start initializing the XMLHTTPRequest object
If (window. XMLHttpRequest ){File: // MozillaBrowser
Http_request = new XMLHttpRequest ();
If (http_request.overridemimetype) {// sets the 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. An error occurred while creating the object instance.
Window. Alert ("the XMLHTTPRequest object instance cannot be created .");
Return false;
}
Http_request.onreadystatechange = processrequest;
// Determine the request sending method and URL and whether to execute the following code synchronously
Http_request.open ("get", URL, true );
Http_request.send (null );
}
// Function for processing the returned information
Function processrequest (){
If (http_request.readystate = 4) {// judge the object status
If (http_request.status = 200) {// The information has been returned successfully. Start to process the information.
Alert (http_request.responsetext );
} Else {file: // The page is abnormal.
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 );
}
}
</SCRIPT>
<Body>
<Form name = "form1" Action = "" method = "Post">
User name: <input type = "text" name = "username" value = "> & nbsp;
<Input type = "button" name = "check" value = "check" onclick = "usercheck ()">
<Input type = "Submit" name = "Submit" value = "/blog/submit">
</Form>
</Body>
</Html>
We can see that JSP is basically the same, except for the URL to be sent: ajax/check. do? Username = "+ username.