从json post方法添加模型属性

时间:2014-05-01 16:22:56

标签: java jquery json spring spring-mvc

我正在使用Spring MVC

我有一个$.ajax POST请求进行一些计算,作为回报,我得到了一个Json对象。

当我这样做时,我可以使用此方法中的model.addattribute(x,y)添加另一个模型属性。

@RequestMapping(value = "/loadPOAction", method = RequestMethod.POST)
public @ResponseBody OrderSearch loadOrder(HttpServletRequest request, Model model,@RequestBody final  OrderSearch search) {

   System.out.println(search.getVal());

  model.addAttribute("name", "to be added to model");
  return search;
}

可行吗?我尝试过,但无法在${name}中获得JSP的价值。

1 个答案:

答案 0 :(得分:0)

无法向先前呈现的JSP添加任何属性。该JSP已被处理并返回给客户端,因此无法访问服务器端上下文。

就跨多个请求重用数据/对象而言,通常会实现缓存策略。这有点超出了您的问题的范围,我建议您在此处阅读:http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#cache

如果要返回包含其他属性的JSON对象,则需要

  • 将值直接添加到search对象(如果它具有必要的字段)
  • 或将所需字段复制到新对象(可以是Map或具体类)

然后返回该对象(相应地调整方法签名)。

例如:

@RequestMapping(value = "/loadPOAction", method = RequestMethod.POST)
public @ResponseBody OrderSearch loadOrder(HttpServletRequest request, @RequestBody OrderSearch search) {

  // set on search object if possible
  search.setName("my name which I retrieved from somewhere");

  // alternatively, you could create a map with the values you need and return it
  // (requires you to change the method return type to Map
  Map<String, Object> resultMap = new HashMap<>();
  resultMap.put("name", "my name");
  resultMap.put("incomingSearch", search);
  resultMap.put("someSearchValue", search.getSomeValue());

  // alternatively, create a new "OrderSearchResponse" class and return an instance of it
  OrderSearchResponse searchResponse = new OrderSearchResponse();
  searchReponse.setName("my name");
  searchResponse.setSomeValue("some value");

  return search; // or resultMap or searchReponse depending on what you do above
}

如果您想渲染另一个JSP ,您可以将方法更改为以下内容(请注意String的返回类型):

@RequestMapping(value = "/loadPOAction", method = RequestMethod.POST)
public @ResponseBody String loadOrder(HttpServletRequest request, Model model, @RequestBody final  OrderSearch search) {

  model.addAttribute("search", search);
  model.addAttribute("name", "to be added to model");

  return "theNameOfYourJspView";
}

然后,在您的theNameOfYourJspView中,您可以使用${search.someValue}以及${name}