java - struts2-rest-插件 : sending json data to PUT/POST

标签 java json rest struts2 struts2-json-plugin

我一直在尝试使用 struts2-rest-plugin 将 JSON 数据发送到 Struts2 REST 服务器。

它适用于 XML,但我似乎无法找出发送它的正确 JSON 格式。

有人有这方面的经验吗?

谢谢, 肖恩

更新:

抱歉我没说清楚。问题是 Struts2 似乎没有将我发送到 Controller 中的模型的 JSON 数据映射。

代码如下:

Controller :

public class ClientfeatureController extends ControllerParent implements ModelDriven<Object> {
    private ClientFeatureService clientFeatureService;

    private ClientFeature clientFeature = new ClientFeature();
    private List<ClientFeature> clientFeatureList;

    //Client ID
    private String id;

    public ClientfeatureController() {
        super(ClientfeatureController.class);
    }

    @Override
    public Object getModel() {
        return (clientFeatureList != null ? clientFeatureList : clientFeature);
    }

    /**
     * @return clientFeatureList through Struts2 model-driven design
     */
    public HttpHeaders show() {
        //logic to return all client features here. this works fine..

        //todo: add ETag and lastModified information for client caching purposes
        return new DefaultHttpHeaders("show").disableCaching();
    }

    // PUT request
    public String update() {
        logger.info("client id: " + clientFeature.getClientId());
        logger.info("clientFeature updated: " + clientFeature.getFeature().getDescription());

        return "update";
    }

    public HttpHeaders create() {
        logger.info("client id: " + clientFeature.getClientId());
        logger.info("feature description: " + clientFeature.getFeature().getDescription());
        return new DefaultHttpHeaders("create");
    }

    public String getId() {
        return id;
    }

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

    public void setClientFeatureService(ClientFeatureService clientFeatureService) {
        this.clientFeatureService = clientFeatureService;
    }

    public List<ClientFeature> getClientFeatureList() {
        return clientFeatureList;
    }

    public void setClientFeatureList(List<ClientFeature> clientFeatureList) {
        this.clientFeatureList = clientFeatureList;
    }

    public ClientFeature getClientFeature() {
        return clientFeature;
    }

    public void setClientFeature(ClientFeature clientFeature) {
        this.clientFeature = clientFeature;
    }
}

这是我向其发出请求的 URL:

..http://localhost:8080/coreserviceswrapper/clientfeature.json

-方法:POST 或 PUT(两种都尝试过,POST 映射到 create(),PUT 映射到 update()) -标题:内容类型:application/json

有效负载:

{"clientFeature":{
        "feature": {
            "id": 2,
            "enabled": true,
            "description": "description1",
            "type": "type1"
        },
        "countries": ["SG"],
        "clientId": 10}
}

当我发出请求时,Struts2 日志中的输出:

1356436 [http-bio-8080-exec-5] WARN  net.sf.json.JSONObject  - Tried to assign property clientFeature:java.lang.Object to bean of class com.foo.bar.entity.ClientFeature
1359043 [http-bio-8080-exec-5] INFO  com.foo.bar.rest.ClientfeatureController  - client id: null

我还要补充一点,XML 请求工作得很好:

URL:..http://localhost:8080/coreserviceswrapper/clientfeature.xml 方法:发布/放置 内容类型:text/xml

有效负载:

<com.foo.bar.entity.ClientFeature>
<clientId>100</clientId>
<feature>
<description>test</description>
</feature>
</com.foo.bar.entity.ClientFeature>

输出:

1738685 [http-bio-8080-exec-7] INFO  com.foo.bar.rest.ClientfeatureController  - client id: 100
1738685 [http-bio-8080-exec-7] INFO  com.foo.bar.rest.ClientfeatureController  - feature description: test
1738717 [http-bio-8080-exec-7] INFO  org.apache.struts2.rest.RestActionInvocation  - Executed action [/clientfeature!create!xml!200] took 1466 ms (execution: 1436 ms, result: 30 ms)

最佳答案

我也遇到同样的问题,我的环境是: 结构 2.3.16.3、Jquery 1.11、Struts-rest-plugin 症状:发布 json 数据,其余 Controller 未将 json 数据解析到模型。 解决方案: 由于 Controller 是模型驱动的,浏览器客户端只需发布 Json 字符串就可以了。但似乎你必须强制 jquery 更改 ajax 调用的内容类型。

_self.update= function(model, callback) {  
          $.ajax({  
              beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
              type: 'PUT',  
              url: this.svrUrl+"/"+ model.id + this.extension,  
              data: JSON.stringify(model), // '{"name":"' + model.name + '"}',  
              //contentType: this.contentType,
              //dataType: this.dataType,  
              processData: false,                   
              success: callback,  
              error: function(req, status, ex) {},  
              timeout:60000  
          });  
      };  

模型数据格式为: var 模型 = {"id":"2", "姓名":"姓名2", "作者":"作者2", “ key ”:“ key 2” }

当您使用“Content-Type”=“application/json”放置或发布数据时,插件将自动使用 Jsonhandler 处理它。

关于java - struts2-rest-插件 : sending json data to PUT/POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12813045/

相关文章:

java - Mac 上的 JDK NoClassDefFoundError

java - 使用 StdDeserializer Jackson 2.5 处理多态

rest - 搜索与特定名称值匹配的子项

JQuery 使用 JSON 数据填充 DropDownList

asp.net-mvc - 为什么我的 ASP.NET Web API 路由可以与 Postman 一起使用,但不能与 Angular Post 请求一起使用

java - 使用高级 rest chrome 打印 json 对象时意外的 token L

java - 必须声明元素类型 "hibernate-mapping"

java - Java 中的异或字节

Java,从不同的引用初始化对象时会有什么不同?

javascript - 当键/值是动态时将 JSON 值转换为数字