【问题标题】:Spring MVC, pass json object to controler and return view with model attributes setSpring MVC,将 json 对象传递给控制器​​并返回带有模型属性集的视图
【发布时间】:2018-01-05 06:56:10
【问题描述】:

我正在尝试将数据发送到我的控制器,让它进行服务调用,然后返回结果以显示在视图上

我的 Ajax 调用如下所示

$.ajax({
            url: "<c:url value="submitReportQuery"/>",
            type: "POST",
            dataType: "html",
            contentType: "application/json;",
            data: JSON.stringify(reportQueryMap),
            success: function (data) {
                $('#SelfServiceResults').html(data);
            }
        })

我的控制器看起来像这样

@RequestMapping(value = "submitReportQuery", method = RequestMethod.POST, consumes="application/json" )
    public String submitReportQuery(@ModelAttribute Map<String, String> reportQueryMap/*, Model model, BindingResult bindingResult*/)throws Exception{
         //model.addAttribute("successful", true);
         return "queries/SelfServiceQueriesSubmitResults";
    }

json 对象看起来像这样(它可以有 0-5 个随机键),我将其作为映射传递给服务 注意:“randomKey”的实际名称可以更改密钥是未知的

{
"randomKey1":"111",
"randomKey2":"222",
"randomKey3":"333",
"reportType":"Commission Processed BH",
"reportProduct":"LIFE",
"reportMonth":"January 2017",
"queryRemark":"nice"
}

我似乎无法将“成功”属性传递给视图,如果我添加注释掉的部分,我会收到此错误

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: java.lang.String submitReportQuery(java.util.Map)

我基本上想要This,但它必须返回一个设置了属性的视图

【问题讨论】:

  • 我认为你应该使用@RequestBody 而不是@ModelAttribute,而且使用类而不是地图会更好(只是我的想法)。

标签: java spring jsp


【解决方案1】:
@RequestMapping(value = "submitReportQuery", method = RequestMethod.POST, consumes="application/json" )
public String submitReportQuery(@RequestBody ReportQueryMapBean reportQueryMap)throws Exception{
     //model.addAttribute("successful", true);
     return "queries/SelfServiceQueriesSubmitResults";
}

public class ReportQueryMapBean {
    // to do delcare the bean fields to match the request
    // and corresponding getter and setter function
}

【讨论】:

  • 我在尝试这个解决方案时得到同样的“java.lang.NoSuchMethodError: java.lang.String submitReportQuery(java.util.Map)”:(
  • 您将 ReportQueryMapBean 更改为 Map
  • 我让它与 ReportQueryMapBean 一起工作,但所有值似乎都是空的
  • 尝试以下更改public class ReportQueryMapBean { private String randomKey1; private String randomKey2; private String randomKey3; private String reportType; private String reportProduct private String reportMonth; private String queryRemark; // to do add getter and setter method for the above fields }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多