Struts2, AJAX, json-plugin to use

Codes, please refer to http://acheron.javaeye.com/admin/blogs/402499

JSON Official Document

http://www.json.org/json-zh.html

jQuery Official Document

http://docs.jquery.com/Main_Page

Js Code

  1. <SPAN> Function removerecordbyid (recordid) (
  2. $ ( "# showallrecord table tr"). each (
  3. function () (
  4. var seq = parseInt ($ (this). children ( "td"). html ());
  5. var thisrecord = this;
  6. if (seq == recordid)
  7. if (confirm ( "you to confirm the implementation of the deletion Yao ?")){
  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 ( "Delete failed, only the ip in order to submit comments to delete");
  16. ) Else (
  17. $ (thisrecord). remove ();
  18. / / Alert ( "deleted successfully");
  19. )
  20. )
  21. error: function () (
  22. alert ( "del error");
  23. )
  24. ));
  25. )
  26. ));
  27. )
  28. function getrecordbypage (page) (
  29. $. ajax ((
  30. type: "POST",
  31. url: "listAllRecordByPage.action",
  32. dataType: "json",
  33. data: ( "page": page),
  34. success: function (json) (
  35. var strs = "<table border=\"1\"> <tr> <td> key-id </ td> <td> nickname </ td> <td> Message Time </ td> <td width = '120 ' "E-mail </ td> <td width='120'> blog </ td> <td width='250'> message </ td> <td> Operation </ td> </ tr>";
  36. for (i = 0; i <json.records.length; i + +) (
  37. str = "<tr'"+json.records[i].id+"'> <td>" + json.records [i]. id + "</ td> <td>" + json.records [i]. from + "</ td> <td>" + json.records [i]. addDate + "</ td> <td>" + json.records [i]. mail + "</ td> <td>" + json.records [ i]. site + "</ td> <td>" + json.records [i]. cont + "</ td> <td> <a'removerecordbyid("+json.records[i].id+");'> Remove </ a> </ td> </ tr> "
  38. strs = strs + str
  39. )
  40. strs = strs + "</ table>"
  41. $ ( "# showallrecord"). html (strs);
  42. )
  43. error: function () (
  44. alert ( "error");
  45. )
  46. ));
  47. ); </ SPAN>

function removerecordbyid(recordid){
                $("#showallrecord table tr").each(
                function(){
                  var seq=parseInt($(this).children("td").html());
                  var thisrecord = this;
                  if(seq==recordid)
                        if(confirm(" You acknowledge that the deletion?  ?")){
                                $.ajax({
                                        type: "POST",
                                        url:"removeRecordById.action",
                                        dataType:"json",
                                        data:{"msg.id":recordid},
                                        success:function(json){
                                                if(json.status==4){
                                                        alert(" Delete fails, only submit messages  ip In order to delete  ");
                                                }else{
                                                        $(thisrecord).remove();
//                                                      alert(" Removed successfully  ");
                                                }
                                        },
                                        error:function(){
                                                alert("del error");
                                        }
                                });
                        }
                });
        }

                function getrecordbypage(page){
                $.ajax({
                        type: "POST",
                        url:"listAllRecordByPage.action",
                        dataType:"json",
                        data:{"page":page},
                        success:function(json){
                                var strs="<table border=\"1\"><tr><td>key-id</td><td> Nickname  </td><td> Message time  </td><td width='120'> Mailbox  </td><td width='120'> Blog  </td><td width='250'> Message  </td><td> Operation  </td></tr>";
                                for(i=0;i<json.records.length;i++){
                                        str="<tr'"+json.records[i].id+"'><td>"+json.records[i].id+"</td><td>"+json.records[i].from+"</td><td>"+json.records[i].addDate+"</td><td>"+json.records[i].mail+"</td><td>"+json.records[i].site+"</td><td>"+json.records[i].cont+"</td><td><a'removerecordbyid("+json.records[i].id+");'> Delete  </a></td></tr>"
                                        strs=strs+str
                                }
                                strs=strs+"</table>"
                                $("#showallrecord").html(strs);
                        },
                        error:function(){
                                alert("error");
                        }
                });

        };

Note dataType: "json" This parameter must not be less, or not correctly identify the

What is a Struts action code

Java code

  1. <SPAN> Public class CrudMsgAction extends ActionSupport (
  2. private Record msg;
  3. private int index;
  4. private RecordService recordService;
  5. private List <Record> records;
  6. private int status = 0;
  7. private int page = 0;
  8. @ JSON (serialize = false)
  9. public RecordService getRecordService () (
  10. return recordService;
  11. )
  12. / / other getter and setter
  13. @ Override
  14. public String execute () throws Exception (
  15. return SUCCESS;
  16. )
  17. / **
  18. * Returns all the records of the JSON data
  19. * @ Return list. All of the record.
  20. * @ Throws Exception
  21. * /
  22. public String listAllRecord () throws Exception (
  23. List <Record> list = recordService.listAllRecord ();
  24. / / List list = Arrays.asList (allRecord);
  25. / / List <Record> list2 = (List <Record>) list;
  26. / / Record rec = (Record) list.get (0);
  27. records = list;
  28. return SUCCESS;
  29. )
  30. public String listAllRecordByPage () throws Exception (
  31. List <Record> list = recordService.listAllRecord (page);
  32. records = list;
  33. return SUCCESS;
  34. )
  35. / **
  36. * Insert Record
  37. * @ Return update the view with AJAX when struts2 action return
  38. * @ Throws Exception
  39. * /
  40. public String insertRecord () throws Exception (
  41. / / Insert the message date is set
  42. msg.setAddDate (new Date ());
  43. / / Get client ip, setIpaddr
  44. String clientIpAddr = ServletActionContext.getRequest (). GetRemoteAddr ();
  45. msg.setIpaddr (clientIpAddr);
  46. / / Determine whether the empty
  47. if ( "". equals (msg.getFrom ())) msg.setFrom ( "anonymous");
  48. if ( "". equals (msg.getMail ())) msg.setMail ("@");
  49. if ( "". equals (msg.getSite ())) msg.setSite ("-");
  50. if ( "". equals (msg.getCont ())) msg.setCont ( "This guy lazy, not really done anything");
  51. recordService.insertRecord (msg);
  52. return SUCCESS;
  53. )
  54. / **
  55. * Through the index to find records
  56. * @ Return the field msg
  57. * @ Throws Exception
  58. * /
  59. public String listRecordByIndex () throws Exception (
  60. List <Record> list = recordService.listAllRecord ();
  61. this. msg = list.get (this. getIndex ());
  62. return SUCCESS;
  63. )
  64. / **
  65. * Remove the corresponding record id
  66. * @ Return field status. In order to update view with AJAX
  67. * @ Throws Exception
  68. * /
  69. public String removeRecordById () throws Exception (
  70. String clientIpAddr = ServletActionContext.getRequest (). GetRemoteAddr ();
  71. Record r = recordService.listRecordById (msg.getId ());
  72. if (clientIpAddr.equals (r.getIpaddr ())){
  73. recordService.removeRecordById (msg.getId ());
  74. return SUCCESS;
  75. )
  76. status = 4;
  77. return SUCCESS;
  78. )
  79. / **
  80. * Access to sub-pages
  81. * @ Return pageSize using field page
  82. * @ Throws Exception
  83. * /
  84. public String getPageSize () throws Exception (
  85. page = recordService.getPage ();
  86. return SUCCESS;
  87. )
  88. ) </ SPAN>

public class CrudMsgAction extends ActionSupport{
        private Record msg;
        private int index;
        private RecordService recordService;
        private List<Record> records;
        private int status = 0;
        private int page = 0;

        @JSON(serialize=false)
        public RecordService getRecordService() {
                return recordService;
        }
//other getter and setter
        @Override
        public String execute() throws Exception {
                return SUCCESS;
        }

        /**
         *  Returns all records of the JSON data
         * @return list . All of the record.
         * @throws Exception
         */
        public String listAllRecord() throws Exception{
                List<Record> list = recordService.listAllRecord();
//              List list = Arrays.asList(allRecord);
//              List<Record> list2 = (List<Record>)list;

                //              Record rec = (Record)list.get(0);
                records = list;
                return SUCCESS;
        }

        public String listAllRecordByPage() throws Exception{
                List<Record> list = recordService.listAllRecord(page);
                records = list;
                return SUCCESS;
        }

        /**
         *  Insert records
         * @return update the view with AJAX when struts2 action return
         * @throws Exception
         */
        public String insertRecord() throws Exception{
                // Insert message date settings
                msg.setAddDate(new Date());
                // Gets the client  ip,setIpaddr
                String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
                msg.setIpaddr(clientIpAddr);
                // Judgment is empty
                if("".equals(msg.getFrom()))msg.setFrom("anonymous");
                if("".equals(msg.getMail()))msg.setMail("@");
                if("".equals(msg.getSite()))msg.setSite("-");
                if("".equals(msg.getCont()))msg.setCont(" This guy is very lazy, nothing left  ");

                recordService.insertRecord(msg);
                return SUCCESS;
        }
        /**
         *  Find a record by index
         * @return the field msg
         * @throws Exception
         */
        public String listRecordByIndex() throws Exception{
                List<Record> list = recordService.listAllRecord();
                this.msg = list.get(this.getIndex());

                return SUCCESS;
        }
        /**
         *  Delete the corresponding ID records
         * @return field status. in order to update view with AJAX
         * @throws Exception
         */
        public String removeRecordById() throws Exception{
                String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
                Record r = recordService.listRecordById(msg.getId());
                if(clientIpAddr.equals(r.getIpaddr())){
                        recordService.removeRecordById(msg.getId());
                        return SUCCESS;
                }
                status = 4;
                return SUCCESS;
        }

        /**
         *  Get pages
         * @return pageSize using field page
         * @throws Exception
         */
        public String getPageSize() throws Exception{
                page = recordService.getPage();
                return SUCCESS;
        }
}

In the above code, the use of the JSON Notes @ JSON (serialize = false),
In addition, JSON Notes also supports several of the fields as follows:
name: specify the Action attribute to be serialized into JSON object's property name.
serialize: settings are the property serialization
deserialize: Set whether to deserialize the property.
format: setting is used to format the output, parse the date form field format. For example, "yyyy-MM-dd'T'HH: mm: ss".

Xml Code

  1. <SPAN> <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <! DOCTYPE struts PUBLIC
  3. "- / / Apache Software Foundation / / DTD Struts Configuration 2.0 / / EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <constant name="struts.objectFactory" value="spring" />
  7. <package name="json" extends="json-default">
  8. <action name="ajaxRequest">
  9. <result type="json" />
  10. </ action>
  11. <action name="listIndexRecord">
  12. <result type="json" />
  13. </ action>
  14. <action name="listAllRecord" method="listAllRecord">
  15. <result type="json" />
  16. </ action>
  17. <action name="listAllRecordByPage" method="listAllRecordByPage">
  18. <result type="json" />
  19. </ action>
  20. <action name="insertRecord" method="insertRecord">
  21. <result type="json" />
  22. </ action>
  23. <action name="removeRecordById" method="removeRecordById">
  24. <result type="json" />
  25. </ action>
  26. <action name="getPageIndex" method="getPageSize">
  27. <result type="json" />
  28. </ action>
  29. </ package>
  30. </ struts> </ SPAN>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.objectFactory" value="spring"/>
        <package name="json" extends="json-default">
                <action name="ajaxRequest">
                        <result type="json" />
                </action>
                <action name="listIndexRecord">
                        <result type="json" />
                </action>
                <action name="listAllRecord" method="listAllRecord">
                        <result type="json" />
                </action>
                <action name="listAllRecordByPage" method="listAllRecordByPage">
                        <result type="json" />
                </action>
                <action name="insertRecord" method="insertRecord">
                        <result type="json" />
                </action>
                <action name="removeRecordById" method="removeRecordById">
                        <result type="json" />
                </action>
                <action name="getPageIndex" method="getPageSize">
                        <result type="json" />
                </action>

        </package>
</struts>

Configure the Action and configuration there is little difference between ordinary Action.

Package inherited the json-default package, rather than inherit the default default package, this is because only under the package only json type Result.
result can be used <param name="excludeProperties"> page, index </ param>
Action does not exclude the return of these properties.

Combined action in the annotation attribute getter method @ JSON (serialize = false) and flexible configuration

Exception address:

Xml Code

  1. Nested in javax.servlet.ServletException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com. googlecode.jsonplugin.JSONException: java.lang.reflect.InvocationTargetException:
  2. com.google.apphosting.utils.jetty.JettyLogger warn

Nested in javax.servlet.ServletException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: java.lang.reflect.InvocationTargetException:

com.google.apphosting.utils.jetty.JettyLogger warn

Here here are 4-5 pages of exceptions, which is not posted out

Solution:

Emergence of this problem is an attribute of data through serialization json abnormal

Since the use of the spring into the properties of recordService, also is to provide a getter and setter,

The sturts-plugin by getterXxx the Xxx output JSON serialization attributes to the client,

Therefore, the methodology is to solve this exception does not require serialization of the property getter added before annotation,

Is @ JSON (Serialize = false)

Code such as:

Java code

  1. @ JSON (serialize = false)
  2. public RecordService getRecordService () (
  3. return recordService;
  4. )

@JSON(serialize=false)

    public RecordService getRecordService() {

       return recordService;

    }
分类:Java 时间:2009-08-20 人气:494
分享到:
blog comments powered by Disqus

相关文章

  • Jquery Ajax.ashx efficient implementation code page 2010-08-28

    First record, so very good page Jquery page is. Ashx file with the. The establishment of three. Ashx, respectively PreviewHandler.ashx, PageHandler.ashx, NextHandler.ashx, respectively, to handle the current page, next page, previous treatment. PageH

  • Recently viewed products Jquery function implementation code 2010-11-25

    Recently viewed products Jquery function implementation code can refer to a friend in need. <script type="text/javascript" src="JS/jquery.js"> </ script> / / and similar frameworks Prototype <script type="text/javas

  • Struts2+Jquery实现ajax并返回json类型数据 2013-06-21

    网上看到很多关于Struts2+ajax+jquery+json的例子,但是很多都不完整,也看不明白,主要原因是返回jsno类型数据和原来的返回字符串类型数据不一样,并且网友们实现步骤没有说清楚,让初学的朋友捉摸不透到底该怎么做. 我做了个简单的demo,供网友们学习,最后我会附上链接,可以下载整个demo. 首先需要的包(struts核心包和json需要的包): struts核心包: json需要的包: commons-logging-*.jar在导入struts核心包的时候就导入了,所以导入

  • js操作ajax返回的json的注意问题! 2013-12-29

    js操作ajax返回的json的注意问题! var result = unescape(xmlhttp.responseText); var j = eval("(" + result + ")"); 不可以 var j = eval( result ); JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧. JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要

  • Jquery ajax不能解析json对象,报Invalid JSON错误的原因和解决方法 2014-04-01

    我们知道Invalid JSON错误导致的json对象不能解析,一般都是服务器返回的json字符串的语法有错误.这种情况下,我们只需要仔细的检查一下json就可以解决问题. 下面说一下,最近在使用jquery 1.4中使用$.ajax()方法解析json对象遇到的问题. Json对象是: [{name:'二手房出售',infoCount:0,pageUrl:'/ershoufang'},{name:'二手房求购',infoCount:0,pageUrl:'/qiugou'},{name:'二手房

  • ajax返回的json内容进行排序使用sort()方法实现 2014-04-10

    关于ajax返回的json内容进行排序,主要使用sort()对数组的元素进行排序,具体实现如下,感兴趣的朋友可以参考下哈,希望对大家有所帮助 关键方法:sort()用于对数组的元素进行排序. return a.num-b.num是升序: return b.num-a.num;是降序 writeln在输出后面加\n,在文档里是换行,在html里是解释称空格. $.post("json.json",function(data){ data.sort(function(a,b){return

  • $.ajax返回的JSON无法执行success的解决方法 2014-11-06

    为什么会这样子呢?在网上查了好久,结果发现是因为我指定了dataType:'json',这样一指定完蛋了,对Json的要求就非常严格起来了 晚上在修改代码,之前用的 $.ajax({ .. dataType:'json', ... success:function(json){ //不执行success }, error:function(error){ //总是执行这个error } }); 为什么会这样子呢?在网上查了好久,结果发现是因为我指定了dataType:'json',这样一指定完蛋

  • AJAX如何接收JSON数据示例介绍 2015-01-03

    如何使用AJAX返回JSON数据,就是dataType,当你设置json后返回的json字符串传递到客户端就是JSON对象了,示例如下,感兴趣的朋友可以参考下 简介 在我们了解如何使用AJAX返回JSON数据的时候要先明白下列几点 1. JSON如何来表示对象的 2. JSON如何来表示数组的 var object = { "labId": "1", "labName": "服装" }; 通常我们使用如上的方式来表示JSON对

  • Small image large-size preview of the implementation code 2010-06-11

    <! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.0 Transitional / / EN"> <html> <head> <title> Javascript Images zoom-out view sample. Brought to you by cutting off dream man. every day QQ: 22062019 </ title> <sc

  • ajax不执行success回调而是执行了error回调 2014-11-27

    最近在看jQuery的API文档,在使用到jQuery的ajax时,如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数,极度郁闷 附上代码如下: JScript code: $.ajax({ type: "post", url: "jsp/loginManager.jsp", data: "name=" + $('#rname').attr('value') + "&pwd=&quo

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.414 (s). 12 q(s)