如何从Spring MVC Controller进行REST调用并按原样返回响应

时间:2014-05-22 18:28:41

标签: json spring-mvc resttemplate

我正在尝试使用RestTemplate从我的Spring MVC控制器进行webservice调用,我想知道是否有一种方法可以返回响应,因为它没有解组到Java对象。

例如在播放框架中,

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

我的大部分回复都是JSON或非常罕见的情况,它可能是一个字符串。

1 个答案:

答案 0 :(得分:3)

这里有一些代码段;

## 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 CODE

// 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>