Use stream-type result to implement Ajax

Source: Internet
Author: User

Struts 2 supports a stream type of result, which can generate binary and text responses directly to the client browser. Then we can let struts 2 action directly generate a text response, and then dynamically load the response on the client page.

For example, the following is a very simple Ajax login example. After the viewer enters the user name and password, we ask him to submit the request asynchronously, the struts 2 action directly outputs the login result-no additional JSP page is required. The following is the action code in this example.

Program list: Codes \ 04 \ 4.6 \ streamajax \ WEB-INF \ SRC \ org \ crazyit \ app \ action \ loginaction. Java

  1. Public class loginaction
  2. Implements action
  3. {
  4. // Encapsulate two attributes of the Request Parameter
  5. Private string user;
  6. Private string pass;
  7. // Encapsulate the binary stream of the output result
  8. Private inputstream;
  9. // The setter and getter methods of the user attribute are omitted.
  10. ...
  11. // The setter and getter methods of the pass attribute are omitted.
  12. ...
  13. Public inputstream getresult ()
  14. {
  15. Return inputstream;
  16. }
  17. Public String execute ()
  18. Throws exception
  19. {
  20. // Determine the user name and password and generate the corresponding response
  21. Inputstream = user. Equals ("crazyit.org") & pass. Equals ("leegang ")
  22. ? New bytearrayinputstream ("congratulations, logon successful! "
  23. . Getbytes ("UTF-8 "))
  24. : New bytearrayinputstream ("sorry, the user name and password do not match! "
  25. . Getbytes ("UTF-8 "));
  26. Return success;
  27. }
  28. }

The preceding actions are roughly the same as Common Logon actions. The user and pass attributes are also provided to encapsulate the user's request parameters, and the setter and getter methods are provided for these two attributes. However, this action is slightly different from a common action. It provides a method to return the binary stream: getresult () -- as shown in the bold text code in the preceding action class.

The binary stream returned by the getresult () method will be directly output to the viewer -- this will be completed using the stream type result, the preceding execute method determines the response based on the user and pass Request Parameters entered by the browser.

Configure the action in the Struts. xml file. The configuration snippets are as follows.

Procedure: Codes \ 04 \ 4.6 \ streamajax \ WEB-INF \ SRC \ struts. xml

  1. <Action name = "loginpro" class = "org. crazyit. App. Action. loginaction">
  2. <Result name = "success" type = "stream">
  3. <! -- Specify the type of response data generated by stream -->
  4. <Param name = "contenttype"> text/html </param>
  5. <! -- Specify the inputstream of the output result returned by the getresult () method -->
  6. <Param name = "inputname"> result </param>
  7. </Result>
  8. <! -- Define a result named login -->
  9. <Result name = "login">/WEB-INF/content/login. jsp </result>
  10. </Action>

Tip: By using stream-type results, strut 2 can generate a specified response directly to the viewer in action without the need for JSP view pages.

Next, you only need to define a login page, which sends an asynchronous request to the loginpro action above and dynamically loads the response sent from the action.

For the sake of simplicity, we will not create XMLHttpRequest objects or send asynchronous requests here. Here we will directly use the Ajax library jquery to send asynchronous requests. The page code is as follows.

Program list: Codes \ 04 \ 4.6 \ streamajax \ WEB-INF \ content \ login. jsp

  1. <% @ Page contenttype = "text/html; charset = GBK" Language = "Java" errorpage = "" %>
  2. <% @ Taglib prefix = "S" uri = "/Struts-tags" %>
  3. <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en"
  4. Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
  5. <HTML xmlns = "http://www.w3.org/1999/xhtml">
  6. <Head>
  7. <Title> use the JSON plug-in </title>
  8. <SCRIPT src = "$ {pagecontext. Request. contextpath}/jquery-1.4.4.min.js"
  9. Type = "text/JavaScript">
  10. </SCRIPT>
  11. </Head>
  12. <Body>
  13. <S: Form ID = "loginform">
  14. <S: textfield name = "user" label = "User Name"/>
  15. <S: textfield name = "pass" label = "password"/>
  16. <Tr> <TD colspan = "2">
  17. <Input id = "loginbn" type = "button" value = "Submit"/>
  18. </TD> </tr>
  19. </S: Form>
  20. <Div id = "show" style = "display: none;">
  21. </Div>
  22. <SCRIPT type = "text/JavaScript">
  23. // Bind the event handler function to the button with the ID loginbn
  24. $ ("# Loginbn"). Click (function ()
  25. {
  26. // Specify to send a request to loginpro, using the ID as the Form Control in the loginform as the Request Parameter
  27. $. Get ("loginpro", $ ("# loginform"). serializearray (),
  28. // Specify the callback function
  29. Function (data, statustext)
  30. {
  31. $ ("# Show"). Height (80)
  32. . Width (300)
  33. . CSS ("border", "1px solid black ")
  34. . CSS ("background-color", "# efef99 ")
  35. . CSS ("color", "# ff0000 ")
  36. . CSS ("padding", "20px ")
  37. . Empty ();
  38. $ ("# Show"). append ("Logon Result:" + Data + "<br/> ");
  39. $ ("# Show"). Show (2000 );
  40. },
  41. // Specify the server response as HTML
  42. "Html ");
  43. });
  44. </SCRIPT>
  45. </Body>
  46. </Html>

In the above program, the bold text code is the code that sends an asynchronous request through jquery. Browse the page in the browser, enter the appropriate user name and password, and then log on to the system. The result shown in 4.34 is displayed.

 

 

In addition, Struts 2.2 also provides a JSON plug-in that can be used for more simple Ajax development. The following describes the Ajax support of struts 2 by taking the JSON plug-in as an example.

Tip: jquery is an excellent and lightweight Ajax function library. It not only provides a large number of convenient tool functions, but also provides simple and powerful Ajax support. If you want to learn more about jquery, see crazy Ajax handout in crazy Java.

This article from the "crazy Java Li Gang" blog, please be sure to keep this source http://javaligang.blog.51cto.com/5026500/895034

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.