Struts2 (ix) using AJAX

Source: Internet
Author: User


Ajax overview

Ajax (Asynchronous JavaScript and XML), asynchronous JavaScript and XML technology, is a web development technique that creates interactive Web applications, derived from a transformation that describes a Web-based application to a data-based application. In data-based applications, data such as user needs, such as contact lists, can be obtained from the server independent of the actual Web page and can be dynamically written to the Web page, improving the slow Web application experience to make it look like a desktop application.

Currently, there are two basic options for writing an application:
1 · Desktop applications
2 · WEB Application
Desktop applications typically require installation to a computer, and desktop applications may use the Internet to download updates, but the code that runs these applications is on the desktop computer. The Web application runs on a Web server somewhere, and is accessed through a Web browser.
The more important question is how the application works and how it interacts with it. Desktop applications are typically very fast (running on the local computer without waiting for an internet connection), with a nice user interface (usually related to the operating system) and extraordinary dynamics. You can click, select, enter, open menus and submenus, cruise around, and basically don't have to wait.
Web applications, on the other hand, are the latest trends that provide services that cannot be implemented on the desktop (such as Amazon.com and EBay). However, with the powerful Web there is waiting, waiting for the server to respond, waiting for the screen to refresh, waiting for the request to return and generate a new page.

Ajax attempts to build a bridge between the functionality of desktop applications and the interactivity of WEB applications that are constantly updated. You try to use a dynamic user interface and nice controls that are common in WEB applications like desktop applications.

The core of Ajax is the JavaScript object XMLHttpRequest. This object was first introduced in Internet Explorer 5, which is a technique that supports asynchronous requests.
XMLHttpRequest is a JavaScript object, and creating the object is simple.

//创建新的 XMLHttpRequest 对象<script language="javascript" type="text/javascript">   var xmlHttp = new XMLHttpRequest();</script>


In a generic WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, the server forwards it to the script that handles the form (usually PHP or Java, or it could be a CGI process or something like that), and the script executes and then sends it back to the new page. The page might be HTML with a new form populated with some data, a confirmation page, or a page with some options selected based on the data entered in the original form. Of course, the user must wait while the script or program on the server processes and returns a new form. The screen becomes blank until the server returns data and then redraws. This is why interactivity is poor, and users don't get immediate feedback, so they feel different from desktop applications.

Ajax basically puts JavaScript technology and XMLHttpRequest objects between Web forms and servers. When a user fills out a form, the data is sent to some JavaScript code instead of being sent directly to the server. Instead, the JavaScript code captures the form data and sends the request to the server. Also, the form on the user's screen does not blink, disappear, or delay. In other words, the JavaScript code sends the request behind the scenes, and the user doesn't even know that the request was made. Better yet, the request is sent asynchronously, meaning that the JavaScript code (and the user) does not wait for the server to respond. So users can continue to enter data, scroll the screen, and use the application.

The server then returns the data to the JavaScript code (still in the Web form), which determines how the data is processed. It can quickly update form data, making it feel that the application is done immediately, that the form is not committed or refreshed, and that the user gets new data. JavaScript code can even perform some sort of calculation on the received data and send another request without user intervention at all! This is the strength of XMLHttpRequest. It can interact with the server as needed, and users can even be completely unaware of what is going on behind the scenes. The result is a dynamic, responsive, highly interactive experience similar to desktop applications, but with all the power of the internet behind it.

In short, XMLHttpRequest allows you to use JavaScript to make requests to the server and handle the response without blocking the user.

There are many examples of such applications, such as Google Suggest using AJAX to create a Dynamic Web interface: When you enter keywords in Google's search box, JavaScript sends these characters to the server, and the server returns a list of search suggestions.

Ajax support for Struts2

Struts2.0 used to encapsulate DWR and dojo in an attempt to provide powerful Ajax support, but starting with struts2.1, STRUTS2 's core functionality no longer provides dojo-based AJAX support, but instead puts Ajax support inside the Dojo plugin.

STRUTS2 supports a stream type of result that can generate binary responses, text responses, and so on directly to the client browser. This allows the STRUTS2 action to generate a text response directly and then dynamically load the response on the client page.

The following is a simple Ajax login example, the user can enter the user name, password, users will be able to submit the request asynchronously, and Struts2 's action directly output the login results, no need to use additional JSP pages. Look at the action class code first.

 PackageCom.afy.app.action;ImportCom.opensymphony.xwork2.Action;Importjava.io.*; Public  class loginaction implements Action{    //Package Two member variables for request parameters    PrivateString user;PrivateString Pass;//Package binary stream of output results    PrivateInputStream InputStream;//user Setter and Getter method     Public void SetUser(String user) { This. user = user; } PublicStringGetUser(){return  This. User; }//Pass Setter and getter method     Public void SetPass(String Pass) { This. pass = Pass; } PublicStringGetpass(){return  This. Pass; } PublicInputStreamGetResult(){returnInputStream; } PublicStringExecute()throwsexception{//Determine user name, password, generate corresponding responseInputStream = User.equals ("crazyit.org") && Pass.equals ("Leegang")            ?NewBytearrayinputstream ("Congratulations, login successful!". GetBytes ("UTF-8"))            :NewBytearrayinputstream ("Sorry, user name, password does not match!" ". GetBytes ("UTF-8"));returnSUCCESS; }}


In addition to what is common in the general Action class, the action provides a method GetResult () that returns a binary stream, and its returned binary stream will be output directly to the browser, which will be done using the result type. The Execute () method determines what response is generated based on the user and pass request parameters entered by the browser.

<?xml version= "1.0" encoding= "GBK"?><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "Http://struts.apache.org/dt Ds/struts-2.3.dtd "><struts>    <constant name="struts.i18n.encoding" value="UTF-8"/>     < package name="Lee"extends= "struts-default">          <action name="Login" class="org.crazyit.app.action.LoginAction ">            <result type="Stream">                <!--Specify the file type for the downloaded file--                <param name="ContentType">Text/html</param>                <!--Specifies that the output result is returned by the GetResult () method InputStream--                <param name="InputName">Result</param>            </result>        </Action>        <action name="*">            <result>/web-inf/content/{1}.jsp</result>        </Action>    </Package ></struts>

Configure the action in Struts.xml.



Result,struts2 using the stream type does not use the JSP view page to generate the specified response directly from the action to the browser.

For simplicity, the tedious steps of creating a XMLHttpRequest object, sending an asynchronous request, and sending an asynchronous request directly from the jquery Ajax Library are not covered here. The page code is as follows.

<%@ page contenttype="text/html; CHARSET=GBK " language=" java " errorpage="" %><%@ taglib prefix="s" uri="/struts-tags" %><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title>Using stream results to implement Ajax</title>    <script src="${pagecontext.request.contextpath}/jquery-1.11.1.js"  Type="Text/javascript">         </script></head><body><s:form id="LoginForm">    <s:textfield name="User" label="username"/>    <s:textfield name="Pass" label="password"/>    <tr><TD colspan="2">    <input id="loginbn" type="button" value=" Submit "/>    </td></tr></s:form><div id="show" style="Display:none;" ></div><script type="Text/javascript">    //For button-bound event handlers with ID loginbn$("#loginBn"). Click ( function(){$("#show"). Hide ();//Specify to send a request to login with the form control in the LoginForm form as the request parameter$.get ("Login", $("#loginForm"). Serializearray (),//Specify callback function             function(data, statustext){$("#show"). Height ( the). Width ( -). CSS ("Border","1px solid black"). CSS ("Border-radius","10px"). CSS ("Background-color","#efef99"). CSS ("Color","#ff0000"). CSS ("padding","20px"). empty (); $("#show"). Append ("Login results:"+ Data +"<br/>"); $("#show"). Show ( -); },//Specify server response as HTML            "HTML"); });</script></body></html>

In addition, struts2.2 provides a JSON plug-in that makes Ajax development easier.

Struts2 (ix) using AJAX

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.