将JSON从Ajax发布到Struts2操作 [英] Posting JSON from ajax to Struts2 Action

查看:64
本文介绍了将JSON从Ajax发布到Struts2操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hey I am trying to post JSON from Ajax to Struts2 action class method. Little more info: I am running client on WAMP server and Struts2 on Eclipse Tomcat.

我的客户端代码:

<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应用程序的东西:

And this is my Java application stuff:

struts.xml :

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 ):

And this is my java code (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控制台看到以下输入:

All the time when I run my client side code, I can see the following input only from Eclipse console:

[]
Getter Call

为什么它是空的?我希望从客户端获得该JSON数组,但不会成功.

Why is it empty? I expect to have that JSON array from client side but no success.

推荐答案

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

To send JSON data via Ajax you need to parse it by the Struts2 json interceptor. It will also populate your data property of the action object, but you should remove ModelDriven fom the action class. Unless you define a property to populate a list data from the json interceptor on the model you can't use model driven with json. To add json interceptor to the action config, you can override its interceptors.

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

这篇关于将JSON从Ajax发布到Struts2操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆