将JSON从ajax发布到Struts2 Action

时间:2014-10-21 18:34:38

标签: java ajax json eclipse struts2

嘿我试图将JSON从Ajax发布到Struts2动作类方法。更多信息:我在WAMP服务器上运行客户端,在Eclipse Tomcat上运行Struts2。

我的客户端代码:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var dataObj = {
"data": [{
    "id": "1",
    "name": "Chris"
}, {
    "id": "2",
    "name": "Kate"
}, {
    "id": "3",
    "name": "Blade"
}, {
    "id": "4",
    "name": "Zack"
}]
};

var data1 = JSON.stringify(dataObj);
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://localhost:8080/Core/add",type: "post", data:  data1, dataType: 'json',      contentType:"application/json;charset=utf-8",async: true,success:function(result){
  $("#div1").html(result);
}});
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>

</body>
</html>  

这是我的Java应用程序:

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">



<struts>

       <package name="addMenu" namespace="/" extends="json-default">

      <action name="registrate" class="com.coreRestaurant.menu.MenuAction">
          <result type="json" >
          <param name="root">json</param>
          </result>
      </action>

      <action name="read" class="com.coreRestaurant.menu.MenuAction" method="readMenuById">
          <result type="json" >
          <param name="root">json</param>
          </result>
      </action>

      <action name="add" class="com.coreRestaurant.menu.MenuAction" method="addMenu">
         <result type="json" >
         <param name="root">data</param>
         </result>
      </action>

   </package>

</struts>

这是我的java代码(MenuAction.java):

    package com.coreRestaurant.menu;

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;

    import com.google.gson.Gson;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;

    public class MenuAction extends ActionSupport implements ModelDriven<Menu>, Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Menu menu = new Menu();

    private String json;

    private List<Menu> data = new ArrayList<Menu>();



    public String execute(){
        MenuService menuService = new MenuService();
        setJson(new Gson().toJson(menuService.getMenuNames()));
        if(menuService.isDatabaseConnectionDown()==false){
            return SUCCESS;
        }else{
            setJson(new Gson().toJson("Failed to connect to Database"));
            return ERROR;
        }
    }

    public String readMenuById(){
        MenuService menuService = new MenuService();
        setJson(new Gson().toJson(menuService.getSpecificalMenuNameById(menu.getId())));
        return SUCCESS;

    }

    public String addMenu(){
        MenuService menuService = new MenuService();
        System.out.println(data);
        for(int i=0; i<data.size(); i++){
            System.out.println(data.get(i));
        }
        menu.setName("Postitus");
        menuService.addMenu(menu);
        return SUCCESS;
    }

    public String getJson() {
        return json;
    }


    public void setJson(String json) {
        this.json = json;
    }


    @Override
    public Menu getModel() {
        return menu;
    }

    public List<Menu> getData() {
        System.out.println("Getter Call");
        return data;
    }

    public void setData(List<Menu> data) {
        System.out.println("Setter Call Flow");
        this.data = data;
    }

}

Menu.java本身:

package com.coreRestaurant.menu;

import java.io.Serializable;

public class Menu implements Serializable{


private static final long serialVersionUID = 1L;
private String name;
private int id;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

}

当我运行客户端代码时,我只能从Eclipse控制台看到以下输入:

[]
Getter Call

为什么空?我希望从客户端获得该JSON数组,但没有成功。

1 个答案:

答案 0 :(得分:1)

要通过Ajax发送JSON数据,您需要通过Struts2 json拦截器解析它。它还会填充操作对象的data属性,但是您应该从操作类中删除ModelDriven。除非您定义一个属性来填充模型上json拦截器的列表数据,否则您不能使用json驱动的模型。要将json拦截器添加到操作配置,您可以覆盖其拦截器。

<action name="add" class="com.coreRestaurant.menu.MenuAction" method="addMenu">
  <interceptor-ref name="json"/>
  <result type="json" >
    <param name="root">data</param>
  </result>
</action>