如何使用 Spring MVC 使用 REST URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8960605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to consume REST URLs using Spring MVC?
提问by Joly
I have developed few RESTful methods and exposed them via Apache Cxf
我开发了一些 RESTful 方法并通过 Apache Cxf 公开它们
I'm developing the client side application using Spring MVC and I'm looking for a simple example to demonstrate how to call/consume these REST methods using Spring MVC
我正在使用 Spring MVC 开发客户端应用程序,我正在寻找一个简单的示例来演示如何使用 Spring MVC 调用/使用这些 REST 方法
I know how to do it using Apache http client but prefer to use Spring MVC in case such this has already been implemented there.
我知道如何使用 Apache http 客户端来做到这一点,但更喜欢使用 Spring MVC,以防这种情况已经在那里实现。
回答by Tomasz Nurkiewicz
Spring provides simple wrapper to consume RESTful services called RestTemplate. It performs path variable resolution, marshalling and unmarshalling:
Spring 提供了简单的包装器来使用 RESTful 服务,称为RestTemplate. 它执行路径变量解析、编组和解组:
Map<String, Integer> vars = new HashMap<String, Integer>();
vars.put("hotelId", 42);
vars.put("roomId", 13);
Room room = restTemplate.getForObject(
"http://example.com/hotels/{hotelId}/rooms/{roomId}",
Room.class, vars);
Assuming Roomis a JAXB object which can be understood by The RestTemplate.
假设Room是一个 JAXB 对象,可以被RestTemplate.
Note that this class has nothing to do with Spring MVC. You can use it in MVC application, but also in a standalone app. It is a client library.
请注意,该类与 Spring MVC 无关。您可以在 MVC 应用程序中使用它,也可以在独立应用程序中使用它。它是一个客户端库。
See also
也可以看看
回答by Abhi
Use path variables to consume REST data. For example:
使用路径变量来使用 REST 数据。例如:
https://localhost/products/{12345}
This pattern should give you the detail of the product having product id 12345.
此模式应为您提供产品 ID 为 12345 的产品的详细信息。
@RequestMapping(value="/products/{productId}")
@ResponseBody
public SomeModel doProductProcessing(@PathVariable("productId") String productId){
//do prpcessing with productid
return someModel;
}
If you want to consume Rest Service from another service then have a look at:
如果您想从另一个服务使用 Rest 服务,请查看:
and
和
http://www.informit.com/guides/content.aspx?g=java&seqNum=546
http://www.informit.com/guides/content.aspx?g=java&seqNum=546

