See how to cast Ajax magic in struts applications

Source: Internet
Author: User
Tags add format array net string split version ruby on rails
Ajax

Ajax is a recent revolution in the Web development process, which allows for a large number of dynamic effects to be configured in a common web browser. Struts has been a de facto standard in java-web development years ago and has been used in a large number of applications. This article will tell you how to combine rich Ajax in your already existing struts application without ы Chung Songhu?

This article will introduce a simple and effective way to incorporate Ajax and struts into your JSP page with some JavaScript. Here we describe how to reuse the existing struts actions, but this technique can also be used for other java-web frameworks you choose. This method can also be translated to the next version of Struts or JSF.

Copyright NOTICE: Any authorized website, reprint, please be sure to retain the following author information and links

Author: Paul Browne;pawenwen (author of Blog:http://blog.matrix.org.cn/page/pawenwen)

Keywords: Struts; Ajax

What is Ajax?

Ajax is the abbreviation for "Asynchronous JavaScript and XML". This is a technique, not a framework like struts. Why is there so much attention around Ajax? This is because Ajax makes Web pages look not like a flat document, but more like a dynamic GUI application that the user expects as a desktop application. Ajax technology can be used in many browsers, including IE and Netscape/mozilla. It is already used by Microsoft (the Web Client for Outlook) and Google (user Google Maps and gmail).

Before Ajax is used

Most struts applications today are the standard structure of "web pages like a flat document." If you want to emulate some desktop applications (such as those built using Java swing,visual Basic, or Delphi), you have two choices: you can send all the information that might be requested as part of the page, Use a lot of JavaScript to manipulate its dynamic display (a slow and non-enterprise Java approach), or you can submit to the backend server without changing the form (an effective method). Ajax improvements give you the best solution for merging the previous solutions: dynamic pages, but most applications are processed on your Web server's Java program.

AJAX 101

Ajax is very similar to the existing dynamic HTML technology and adds a request to the "back-end" server to get the new or updated information needed. The AJAX mechanism has been explained in detail elsewhere-please check the resources in this article for more information. But you need to know at least:

1. XMLHttpRequest (if you are using IE browser, it is microsoft.xmlhttp ActiveX object). These objects, you can use JavaScript calls in Web pages. They allow you to request the content of the Web server as a background call (for example, after a form is submitted, the screen does not display "blank" as usual).

2. The content returned by XMLHttpRequest and Microsoft.XMLHTTP can be processed as XML or text. JavaScript (on your page) can use the new content of the request to update the page.

3. The entire process can be triggered by ordinary JavaScript events: Onclick,onchange,onblur, etc.

Use Ajax in your struts application

You read this article, and then you're interested in using AJAX to create dynamic Web pages, and you want to know how to add it to your struts application. It's just one of the options. So how would you choose?

· Wait, knowing that the next version of Struts blends Ajax technology. If struts developers are ready to develop a new application, this might be a good choice. And then again, it might be asking JSF to do the same-it's not a bad thing for itself, but it's going to be the most fundamental change for a system that already exists.

· You can also use new methods, such as direct Web Remoting (DWR) and Ruby on Rails, which are designed for AJAX applications. If you consider not using struts to develop the web, then these are all very good frameworks and worth a try. However, it also means that you have to rewrite your application.

· Add Ajax to your already existing struts application. Since Ajax is just a technology, not a framework, it's easy to fit into struts. As an existing system, its stability (e.g., maintaining existing library files) is quite important. So this method is recommended, and we'll explain in detail later.

The advantages we choose to add to Ajax in struts applications are:

1. It does not require any new library files or server code, just use existing Struts library files and action.

2. All parts of the solution ――javascript,xml,java and struts―― have long been known.

3. This application can be ported together to Ajax; we can determine which parts are good for the user and first update them to the dynamic AJAX display.

Implementation scenarios

How do we truly implement our choices? We should first note how a "standard" (without Ajax) Struts application works. In this application, a general event flow is as follows:

1. The user sends the request using the click of the hyperlink or the Submit button of the form.

2. The Web server runs a struts action that handles the request to generate a Web page.

3. Browsers display Web pages.

4. When the user clicks on the save, the information is converted by a Actionform class in the struts framework and sent to the server.

5. The struts framework then calls the struts action to come out and request (e.g., save the data to the database).

6. The page again, the processing process continues.

The existing Struts application

A simple struts application demonstrating the event flow can be downloaded at the following address: Struts-non-ajax.zip. This application based on struts is to display or hide blue and green tables based on user input. Figure 1 shows the screen that loads the initial page. Figure 2 shows the user input value and clicks on the submitted screen. Although simple, it is enough to represent a struts workflow.

Figure 1. No Ajax examples: splash screen

Figure 2. No AJAX examples: input values and click on Submit

The server-side code is: a Struts action forwards the (same) JSP using the values defined in Struts-config.xml. Some of the things to note in this example code are:

The struts-config.xml file redirects all requests to the index.jsp of http://localhost:8080/struts-non-ajax/(or the same as your own server).

· Index.jsp contains a two-text-box struts form (Showblue and Showgreen). The page also contains labels, but as two text boxes are initialized to empty, the contents of the labels do not appear.

· The user enters the value (TRUE or FALSE) and clicks the submit button, processing control (after the Struts framework, read Struts-config.xml) commits to the Sampleaction class.

· Sampleaction records the value and forwards it to index.jsp. A mature struts application may handle more things than save or query the database.

· Index.jsp now processes the request, and if Showblue or Showgreen values are true, the tables are displayed.

The application does not have any "errors". Similar struts projects have done this for many years. But how do we add dynamic elements to this application without adding complex JavaScript or frequent form submissions?

Our first Struts AJAX application

Look at Figure 3 and figure 4 below. At first glance, they don't differ from the previous examples. The difference is that when the page is loaded (Figure 3) and then the value in the text box changes, the form is automatically submitted without white space, and the results are displayed in Figure 4. The regular submit button is still there and you can choose to use it.

Figure 3. Ajax examples of page loading

Figure 4. Ajax examples after Ajax calls

Adding Ajax is surprisingly easy. The server-side code is the same as the previous example: a struts actionform to go after the data, a struts action to perform the required tasks (for example, storage database) and then forward to the appropriate JSP page to display the results.

Go on

If you want to stop reading this (skip the work instructions for this example), but here is the same style that you need to convert your struts application to a STRUTS-AJAX application:

1. Introduce a ajax.js in your Web page (this file is part of the struts-ajax.zip example file). Ajax.js contains all the JavaScript methods that need to send and receive Ajax calls.

2. Make sure that the part of the Web page you want to update in the AJAX call is included in the label and give each label an ID.

3. When some events are triggered, update the page (for example, the onchange () method of the text box), call the Retrieveurl () method, and pass the URL to the struts Action that needs to perform server-side processing.

4. The simplest way to display/update the page is to forward the struts action back to the same page. In this case, the onchange () method in the Showgreen/showblue text box triggers the AJAX call.

The JavaScript Method Retrieveurl () invokes the server's struts (through the URL), gets the JSP response, and then updates the portion of the label in the Display page. It's so simple!

Details of the Ajax solution

When we turn the example into a ajax-struts application, we need three changes:

1. Add a JavaScript method to complete the "behind" Ajax call to the server.

2. Add JavaScript code to receive the response from the server and update the page.

3. Add tag tags to the JSP page, and the contents of this tab will be updated in the AJAX call.

We will explain each step of the above in detail.

Sending AJAX requests to the server

There are two methods (listed below) for sending requests to the server.

· The Retrieveurl () method obtains the server's URL and struts form. URLs are used to use ajax,form values for delivery to the server.

· The Getformasstring () method assembles the value named in the Retrieveurl () into a query string and sends it to the server.

Using the method is simple, use the onclick ()/onchange () event to trigger the Retrieveurl () update display.

There are some interesting things in these two methods.

In the Retrieveurl () method, Req.onreadystatechange = Processstatechange (Note that there are no parentheses) this line tells the browser to call Processstatechange when the server response arrives () Method (This method is described later). The Retrieveurl () method (now the standard for Ajax) also determines whether to use IE browser (ActiveX) or use Netscape/mozilla (XMLHttpRequest) to achieve cross-browser compatibility.

The Getformasstring () method converts the HTML form to a string connection behind the URL (this allows us to send an HTTP GET request). The string is converted (for example, the space is converted to%20, and so on) and is a format that struts can assemble into actionform (no need for struts to clearly understand that this is an AJAX request). Note that in this example we use HTTP GET, and the method of using the HTTP POST is similar.

function Retrieveurl (url,nameofformtopost) {

Converting URLs to Strings

Url=url+getformasstring (Nameofformtopost);

Invoke Ajax

if (window. XMLHttpRequest) {

Non IE browser

req = new XMLHttpRequest ();

Req.onreadystatechange = Processstatechange;

try {

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

catch (e) {

Alert ("Server communication problem\n" +e);

}

Req.send (NULL);

else if (window. ActiveXObject) {

Ie

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

if (req) {

Req.onreadystatechange=processstatechange;

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

Req.send ();

}

}

}

Getformasstring () is a "private" method that is used in Retrieveurl ().

function getformasstring (formName) {

Set return string

returnstring = "";

Get the value of a form

formelements=document.forms[formname].elements;

Loop array, assembly URL

A format like '/strutsaction.do&name=value '

for (var i=formelements.length-1;i>=0;-I.) {

Convert each value

returnstring+= "&"

+escape (formelements[i].name) + "="

+escape (Formelements[i].value);

}

return string

return returnstring;

}

Update a Web page based on AJAX response

So far, we've learned to use JavaScript to complete Ajax calls (listed above), Struts Action,actionform and JSPs (basically unchanged, just adding tags). To refine our understanding of the Struts-ajax project, we need to know three JavaScript methods used to update the page based on the results returned by the server.

· Processstatechange (): This method is set before the AJAX call. It is invoked by the Xmlhttprequest/microsoft.xmlhttp object after the server response arrives.

Splittextintospan (): According to the response, loop out the elements in the array to assemble into newcontent.

replaceexistingwithnewhtml (): According to the span element array, loop the search, and replace the elements inside the page with its ' somename ' in the same content. Note that we are using the Req.responsetext method to get the returned content (it allows us to manipulate the response of any text). This is relative to Req.responsexml (it works more, but requires that the server return is XHTML or XML).

function Processstatechange () {

if (req.readystate = = 4) {//complete

if (Req.status = = 200) {//responding to normal

Splits the text of a response into a SPAN element

Spanelements =

Splittextintospan (Req.responsetext);

Update pages with these span elements

Replaceexistingwithnewhtml (spanelements);

} else {

Alert ("Problem with server response:\n"

+ Req.statustext);

}

}

}

Replaceexistingwithnewhtml () is a "private" method used for Processstatechange ().

function replaceexistingwithnewhtml

(newtextelements) {

Cycle newtextelements

for (Var i=newtextelements.length-1;i>=0;--i) {

Determine if the if (Newtextelements[i].

IndexOf ("-1") {

Get the name of span-set between the first and second quotes

Verify that the span element is in the following format

Newcontent

Startnamepos=newtextelements[i].

IndexOf (' ") +1;

Endnamepos=newtextelements[i].

IndexOf (' "', Startnamepos);

Name=newtextelements[i].

SUBSTRING (startnamepos,endnamepos);

Get content-All content after the first > tag

Startcontentpos=newtextelements[i].

IndexOf (' > ') +1;

Content=newtextelements[i].

SUBSTRING (startcontentpos);

Now update the elements in the existing document,

Make sure that this element exists in the document

if (document.getElementById (name)) {

document.getElementById (name).

InnerHTML = content;

}

}

}

Splittextintospan () is a "private" method used for Processstatechange ().

function Splittextintospan (texttosplit) {

Split document

Returnelements=texttosplit.

Split ("")

Process each element

for (Var i=returnelements.length-1;i>=0;--i) {

Delete the elements behind the first span

Spanpos = Returnelements[i].

IndexOf ("

If you find a match, get the contents of the span before

if (spanpos>0) {

Substring=returnelements[i].

SUBSTRING (spanpos);

returnelements[i]=substring;

}

}

return returnelements;

}

New Control Flow

Add the following JavaScript code to our application, and the following steps will be performed in the server and in the browser.

1. Like a common Struts application loading page.

2. The user changes the value of the text box, triggers a onchange () event, and invokes the Retrieveurl () method.

3. The JavaScript method requests a struts Action to the server by sending a clear form variable (background) to the struts.

4. The JavaScript method also sets the name of the second JavaScript method, which is invoked after the server response completes. In this example, the Processstatechange () method is set.

5. As we expected, the server responded and called the Processstatechange () method.

6. JavaScript loops out all the elements in the (new) server response. Replaces the elements in the page that are in the same name as the obtained element.

Designing Ajax in your application

The JavaScript method described above can be used in most applications, including much more complex than our example. However, before using, you need to pay attention to the following points:

· Avoid copying code, preferably using the same struts action and JSP in the initialization request (e.g., displaying the full page) and Ajax (update part Page) requests.

• In a public action (Controller), a region that determines the JSP page (all JSP pages or a portion of it) needs to be routed to the browser. Let the JSP page know which parts need to be submitted by setting the tag in the session or Actionform of the Web server.

· In the JSP, use struts or JSTL tags to determine the submitted HTML area.

This example of using Ajax can be downloaded in the following: Struts-ajax.zip

Conclusion

Ajax technology allows us to completely change when creating and using Web applications. This article introduces a simple technique to increase the processing of struts in existing struts applications. It allows us to take advantage of what we already have, not just code, but also development skills. As a good product, it also allows us to write a clearer, more portable Java struts application.

Resources

• Author's Blog:http://blog.matrix.org.cn/page/pawenwen

· Sample code for this article

· Definition of AJAX

· "Using AJAX to Catch JavaScript Errors" (xml.com article)

· "Developing AJAX applications The Easy Way" (java.net article)

· "An Introduction to AJAX" (Dev2dev article)

·" AJAX on Rails "(onlamp.com article)

· Dwr:direct Web Remoting Project

· Struts Framework Project

· Jsf:java Server Faces Project

Paul Browne has been working for firstpartners.net for more than 7 years as an enterprise-class Java consultant.



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.