【问题标题】:How to make a REST call from Spring MVC Controller and return the response as it is如何从 Spring MVC 控制器进行 REST 调用并按原样返回响应
【发布时间】:2014-07-11 22:44:19
【问题描述】:

我正在尝试使用 RestTemplate 从我的 Spring MVC 控制器进行 Web 服务调用,我想知道是否有一种方法可以在不解组到 Java 对象的情况下按原样返回响应。

比如在play框架中,

HttpResponse res = WS.url(url).get(); renderJSON(res.getString()); // or res.getJson()

我的大部分响应都是 JSON,或者在极少数情况下它可能是字符串。

【问题讨论】:

  • 如果客户端返回字符串作为 Web 服务的响应,则不需要解组。您可以按原样传递字符串。
  • Santosh 正如我大部分时间提到的它的 JSON。我不想在我的应用程序中使用 POJO,我只需要将响应转发回来。基本上我想看看是否有类似 play framework 的等价选项。
  • 我们以前做的是,调用一个webservice得到一个json响应,在sring mvc模型中设置响应给client(ui)端使用。在客户端,我们有 angular js,它按原样使用这个提要。
  • 你能分享那个代码吗?猜猜它对我也有用。我使用 JQuery 而不是 Angular。
  • 将代码添加到答案中,希望能奏效。

标签: json spring-mvc resttemplate


【解决方案1】:

这里有一些代码 sn-p;

## JAVA代码

@Autowired
RestOperations operations;

@RequestMapping(method = RequestMethod.GET)
    public String index( @PathVariable("id") String id, Model model) {

    //a) Call webservice using restemplate or using any other method
    //b) get the data from service
    //c) set data in modal

    String jsonFeed = operations.getForObject("URL", String.class);
    model.addAttribute("jsonFeed", jsonFeed);
}

## JSP 代码

// fetch the jsonFeed variable set in the modal attribute and set it into a java script variable and use the way u want.

<script type="text/javascript">
       var jsonObjToUse = jQuery.parseJSON(${jsonFeed})
 </script>

【讨论】:

  • 我错过的是 JQuery.parseJSON 部分。感谢分享代码。
猜你喜欢
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多