Integrate jQuery to implement Ajax functions in Struts2 (2)

Source: Internet
Author: User
Tags sendmsg string back

Integrate jQuery to implement Ajax functions in Struts2 (2)

1.1.1 Action responds to Json format information using struts2-json-plugin-X.X.X.jar:

1. function removerecordbyid (recordid ){

2. $ ("# showallrecord table tr"). each (

3. function (){

4. var seq = parseInt ($ (this). children ("td" pai.html ());

5. var thisrecord = this;

6. if (seq = recordid)

7. if (confirm ("are you sure you want to perform the delete operation? ")){

8. $. ajax ({

9. type: "POST ",

10. url: "removeRecordById. action ",

11. dataType: "json ",

12. data: {"msg. id": recordid },

13. success: function (json ){

14. if (json. status = 4 ){

15. alert ("deletion failed, only the ip address that submitted the message can be deleted ");

16.} else {

17. $ (thisrecord). remove ();

18. // alert ("deleted successfully ");

19 .}

20 .},

21. error: function (){

22. alert ("del error ");

23 .}

24 .});

25 .}

26 .});

27 .}

Action Code (simplified)

1. public class CrudMsgAction extends ActionSupport {

2. private Record msg;

3. private int index;

4. private RecordService recordService;

5. private List Records;

6. private int status = 0;

7. private int page = 0;

8.

9. @ JSON (serialize = false)

10. public RecordService getRecordService (){

11. return recordService;

12 .}

13.

14 ./**

15. * return JSON data of all records

16. * @ return list. All of the record.

17. * @ throws Exception

18 .*/

19. public String listAllRecord () throws Exception {

20. List List = recordService. listAllRecord ();

21. records = list;

22. return SUCCESS;

23 .}

24.

25. public String listAllRecordByPage () throws Exception {

26. List List = recordService. listAllRecord (page );

27. records = list;

28. return SUCCESS;

29 .}

30.

31 ./**

32. * Insert record

33. * @ return update the view with AJAX when struts2 action return

34. * @ throws Exception

35 .*/

36. public String listRecordByIndex () throws Exception {

37. List List = recordService. listAllRecord ();

38. this. msg = list. get (this. getIndex ());

39.

40. return SUCCESS;

41 .}

42 ./**

43. * Delete the corresponding id record

44. * @ return field status. in order to update view with AJAX

45. * @ throws Exception

46 .*/

47. public String removeRecordById () throws Exception {

48. String clientIpAddr = ServletActionContext. getRequest (). getRemoteAddr ();

49. Record r = recordService. listRecordById (msg. getId ());

50. if (clientIpAddr. equals (r. getIpaddr ())){

51. recordService. removeRecordById (msg. getId ());

52. return SUCCESS;

53 .}

54. status = 4;

55. return SUCCESS;

56 .}

57.

58./** obtain the page number */

59. public String getPageSize () throws Exception {

60. page = recordService. getPage ();

61. return SUCCESS;

62 .}

63 .}

In the code above, @ JSON (serialize = false) is used ),
In addition, @ JSON also supports the following fields:
Name: Specifies the property name of the JSON object that the Action property is serialized.
Serialize: sets whether to serialize this attribute.
Deserialize: sets whether to deserialize this attribute.
Format: format used to format the output and parse the date form fields. For example, "yyyy-MM-dd't'hh: mm: ss"

1. <package name = "json" extends = "json-default">

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

There is a small difference between configuring this Action and configuring a common Action.

The package inherits the json-default package, instead of the default package. This is because only the package has the json type Result.
Result can be usedPage, indexExclude the attributes that are not returned in the Action.

We only need to output the name attribute value of the person object. The configuration is as follows:

1.

2.Person. name

3.

ExcludeNullProperties: whether to remove the null value. The default value is false.

4.

5.True

6.

IgnoreHierarchy parameter: Indicates whether to ignore the level, that is, the inheritance relationship. For example, if TestAction inherits from BaseAction, The json string returned by TestAction does not include the attribute value of the parent class BaseAction by default, the default value of ignoreHierarchy is true.

7.

8.False

9.

IncludeProperties parameter: attribute value to be included in the output result. Here, the regular expression matches the attribute name. You can use commas (,) to separate multiple regular expressions. For example, all attributes of person are output.

10.

11.Person. *, person/. name

12.

For example:

"Yushou_hetong"Extends = "Json-default"Namespace = "/Pages/hetong">

"HetongAdd"Class ="HetongAddAction">

"List">/Pages/hetong/qylist. jsp

"Add">/Pages/hetong/add.html

"Query">/Pages/hetong/query.html

"Xiangmu">/Pages/hetong/add/xiangmu. jsp

"Loupan">/Pages/hetong/add/loupan. jsp

"House">/Pages/hetong/add/house. jsp

"HouseList">/Pages/hetong/add/houseList. jsp

"Fukuan">/Pages/hetong/add/fukuan. jsp

"Success"Type = "Json">

"IgnoreHierarchy"> False

"IncludeProperties"> Errmsg

Level 2 linkage tag

Implement the event based on the struts2 tag s: doubleselect second-level linkage Tag: Call struts2 action when the second-level onchange, query a name in the action, and return the result, this information is displayed on the page (this only gives the user a prompt, does not affect whether the form can be submitted)

Jsp code that requires second-level interaction with events

1.Class= "AlignLeft" width = "22%"> business/Project name:

2.Class= & Quot; alignLeft & quot; width = & quot; 20% & quot;>

3.

4. listValue = "operationName" doubleList = "operationSubProductList"

5. doubleListKey = "id" doubleListValue = "prudName" doubleName = "changeApplyFormBO. productId"

6. headerKey = "" headerValue = "--- Please Select ---"/>

7.

8.

We need to call the function under the event where the "Project name" is changed. In the generated static page, we can find that its id is cbApplySubmit_changeApplyFormBO_productId.

Note that the IDS generated here are somewhat regular and look like this. CbApplySubmit is the action of the form on this page, while changeApplyFormBO. productId is the name of "project name ".

The js of the custom drop-down menu event is shown below.

1. <script>

2.

3. $ (Function(){

4.VarObj = document. getElementById ("cbApplySubmit_changeApplyFormBO_productId ");

5. obj. onchange =Function(){

6.VarProdId = obj. value;

7.VarUrl = "$ {contextPath}/assets/businessChange/ajaxGetCompany. do ";

8.VarJsonProd = {productId: prodId}; // JSON object

9.VarProdStr = JSON. stringify (jsonProd); // converts a JSON object into a JSON string.

10. $. post (url, {json: prodStr}, callback, "json ");

11 .}

12.FunctionCallback (json ){

13. $ ("# company" cmd.html (json. msg );

14 .}

15 .});

16.

17. </script>

Here, whether sent from the browser (JS, Ajax, Jquery, etc.) to the server, or from the server (Struts Action, Servlet, etc.) back to the client, all sent strings are in JSON format.

Explanation:

1.VarJsonProd = {productId: prodId };

This statement is to assemble a JSON object. The key is productId, and the value is the id of the project name selected on the page.

1. // convert a JSON object into a JSON string

2.VarProdStr = JSON. stringify (jsonProd );

Convert a JSON object to a string using the stringify method of the built-in JSON object in JavaScript. This is because the strings in JSON format are sent to the server.

1. $. post (url, {json: prodStr}, callback, "json ");

In this sentence, jquery uses the POST method to send data to the server. The url is the full path of the action to be called, and {json: prodStr} is the data to be sent ), {json: prodStr} is actually a JSON object in the form of Key: value. Note that when we send the json string prodStr, to receive the variable "json", the value of this variable is the prodStr string we sent.

Callback refers to the function executed on JS when the server returns a successful result. The last parameter "json" is a type of returned data. In addition, it includes "text" and "xml ".

FunctionCallback (json ){

1. $ ("# company" cmd.html (json. msg );

2 .}

3 .});

Company is the id of span. See the top secondary linkage tag. This function is used to display the value of the json object assembled in the action.

Struts2 action class

1.ImportOrg. json. JSONObject;

2.

3.Public classCBApplyActionExtendsActionSupport {

4.PrivateIProductMng productMng;

5.PrivateString json;

6 ./**

7. * by selecting a project name, a prompt message indicating the business department name is displayed.

8 .*

9. * @ return

10. * @ throws Exception

11 .*/

12.Public voidAjaxGetCompany ()ThrowsException {

13. JSONObject jsonObj =NewJSONObject (json); // construct a JSON string into a JSON object

14.

15. String productId = jsonObj. getString ("productId"); // obtain the value of the productId attribute in the JSON object

16.

17. ProductBO prod = productMng. loadProduct (Integer. parseInt (productId ));

18. Integer companyId = prod. getCompanyId ();

19. CompanyBO comp = productMng. loadCompany (companyId );

20. String companyName = "Business Unit:" + comp. getName ();

21. json = "{msg: '" + companyName + "'}"; // construct a JSON string

22. sendMsg (json); // send a JSON string back to the JS end.

23 .}

24.

25.Public voidSendMsg (String content)ThrowsIOException {

26. HttpServletResponse response = ServletActionContext. getResponse ();

27. response. setCharacterEncoding ("UTF-8 ");

28. response. getWriter (). write (content );

29 .}

30.

31.PublicString getJson (){

32.ReturnJson;

33 .}

34.

35.Public voidSetJson (String json ){

36.This. Json = json;

37 .}

38.

39.Public voidSetProductMng (IProductMng productMng ){

40.This. ProductMng = productMng;

41 .}

42 .}

JSONObject is a json website. The javasajaxgetcompany method does not return a String as the struts2 method does. Here, void is set, because we do not need to jump any way.

Note that json = "{msg: '" + companyName + "'}"; companyName should be enclosed in quotation marks.

Struts2 configuration file

1. class= "CBApplyAction"

2. method = "ajaxGetCompany">

3.

No result

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.