How to get json object using its key value in Struts?

前端 未结 1 1081
清歌不尽
清歌不尽 2020-12-20 10:21

I am working on web services in struts. Now I want json object using its key value. Then I have to post something like array in response. I have no idea how to do that in St

相关标签:
1条回答
  • 2020-12-20 11:01

    Working with JSON not necessary to send JSON to Struts. Even if it could be configured to accept JSON content type, it won't help you. You can use ordinary request to Struts with the data passed in it. If it's an Ajax call then you can use something like

    $.ajax({
       url: "<s:url namespace="/aaa" action="bbb"/>",     
       data : {key: value},
       dataType:"json",
       success: function(json){
         $.each(json, function( index, value ) {
           alert( index + ": " + value );
         });
       }
    }); 
    

    The value should be an action property populated via params interceptor and OGNL. The json returned in success function should be JSON object and could be used directly without parsing.

    You need to provide action configuration and setter for the property key.

    struts.xml:

    <package name="aaa" namespace="/aaa"  extends="json-default">
      <action name="bbb" class="com.bbb.Bbb" method="ccc">
       <result type="json">
         <param name="root">
       </result>
      </action> 
    </package>
    

    This configuration is using "json" result type from the package "json-default", and it's available if you use struts2-json-plugin.

    Action class:

    public class Bbb extends ActionSupport {
    
      private String key;
      //setter
    
      private List<String> value = new ArrayList<>();
      //getter
    
      public String ccc(){
        value.add("Something");
        return SUCCESS;
      }
    } 
    

    When you return SUCCESS result, Struts will serialize a value property as defined by the root parameter to the JSON result by invoking its getter method during serialization.

    If you need to send JSON to Struts action you should read this answer.

    0 讨论(0)
提交回复
热议问题