How to consume REST URLs using Spring MVC?

后端 未结 2 1519
攒了一身酷
攒了一身酷 2020-12-29 13:54

I have developed few RESTful methods and exposed them via Apache Cxf

I\'m developing the client side application using Spring MVC and I\'m looking for a simple examp

相关标签:
2条回答
  • 2020-12-29 14:20

    Spring provides simple wrapper to consume RESTful services called RestTemplate. It performs path variable resolution, marshalling and unmarshalling:

    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 Room is a JAXB object which can be understood by The 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.

    See also

    • REST in Spring 3: RestTemplate
    0 讨论(0)
  • 2020-12-29 14:22

    Use path variables to consume REST data. For example:

    https://localhost/products/{12345}

    This pattern should give you the detail of the product having product 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:

    http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html

    and

    http://www.informit.com/guides/content.aspx?g=java&seqNum=546

    0 讨论(0)
提交回复
热议问题