Action to accept dynamic json data from user interface

后端 未结 2 1708
青春惊慌失措
青春惊慌失措 2020-12-01 23:13

I would like to have an Action class which should accept a JSON string constructed from user interface with no setter and getter in the Action clas

2条回答
  •  天涯浪人
    2020-12-01 23:39

    If you want to send JSON object with multiple key-value pair in it and you want to get these key-values in your action class without creating any setters/getters,

    In the Action class decleration, we should implement ServletRequestAware and we should override the setServletRequest() method and set the HttpServletRequest attribute

    public class YourClass extends ActionSupport implements ServletRequestAware
    
    private HttpServletRequest request;
    
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    
    public HttpServletRequest getServletRequest() {
      return this.request;
    }
    

    And in our targeted function, we should use above request object to get the parameter (by its name as it is set in the json as the key):

    public String fetchData() {
      String key1Data = getServletRequest().getParameter("key1");
       String key2Data = getServletRequest().getParameter("key2"); 
      return SUCCESS;
     }
    

    Where your JSON object should have data something like:

    var jsonData = {"key1": "Hello", "key2":"There"};
    

提交回复
热议问题