0

在服务器上使用 Spring MVC,我们有你的基本 REST API:

@Controller
@RequestMapping(value="/entities")
public class EntityController
{

    //GET /entities
    @RequestMapping(method=RequestMethod.GET)
    @ResponseBody 
    public List<Entity> getEntities()
    ...

    //GET /entities/{id}
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    @ResponseBody 
    public Entity getEntity(@PathVariable Long id)
    ...

    //POST /entities
    @RequestMapping(method=RequestMethod.POST, consumes="application/json")
    @ResponseBody 
    public Entity createEntity(@RequestBody Entity entity) 
    ...

    //PUT /entities
    @RequestMapping(method=RequestMethod.PUT, consumes="application/json")
    @ResponseBody 
    public Entity updateEntity(@RequestBody Entity entity)
    ...
}

这一切都很好。现在我希望能够Entity通过一个请求创建或更新多个 s。我的第一个想法是添加这个:

@RequestMapping(method=RequestMethod.PUT, consumes="application/json")
@ResponseBody
public List<Entity> updateEntities(@RequestBody List<T> entities)

它将具有与updateEntity但处理列表 ( [...]) 相同的 URL。将updateEntity处理单个对象 ( {...})。但是,在服务器启动时出现以下错误:

java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'entityController' bean method public java.util.List<foo.bar.Entity> foo.bar.EntityController.updateEntities(java.util.List<foo.bar.Entity>) to {[/entities],methods=[PUT],params=[],headers=[],consumes=[application/json],produces=[],custom=[]}: There is already 'entityController' bean method public foo.bar.Entity foo.bar.EntityController.updateEntity(foo.bar.Entity) mapped.

因此,据我所知,Spring 不喜欢使用相同的两种不同方法@RequestMapping,即使它们@RequestBody不同。

这让我想到了两个问题。首先,我是否以正确的 RESTful 方式进行处理?当我对同一个 URL 执行 PUT 并且只允许请求正文是单个对象或列表时,我是否符合 RESTful 原则?Spring想要另一种正确的方法吗?(好吧,所以第一个问题实际上是三个......)

第二个问题是我是否可以在@RequestMapping注释中添加一些东西来充分区分这两种方法,但保持相同的 REST API?

感谢您对此有所了解。

4

1 回答 1

0

每个模型的@JsonIgnoreProperties(ignoreUnknown = true)

我已经这样做了......有两个模型:用户和树

@RequestMapping(value = "/users/testBean", method = RequestMethod.POST, consumes={"application/json","application/xml"}, produces={"application/json","application/xml"}) 
    public @ResponseBody List<User> testBean(@RequestBody Object object) {
        System.out.println("testBean called");
        System.out.println(object.toString());

        ObjectMapper mapper=new ObjectMapper();

        User user =mapper.convertValue(object, User.class);
        Tree tree =mapper.convertValue(object, Tree.class);

        System.out.println("User:"+user.toString());
        System.out.println("Tree:"+tree.toString());
        return userService.findAll();
    }
于 2013-06-13T05:05:02.647 回答