在服务器上使用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
。我的第一个想法是添加这个:
@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
不同。
这引出了两个问题。首先,我是否采用正确的REST方式?当我对相同的URL进行PUT并且仅允许请求主体是单个对象或列表时,我是否符合RESTful原则?春天会有另一种正确的方法吗? (好的,所以第一个问题实际上是三个......)
第二个问题是,我是否可以在@RequestMapping
注释中添加一些能够区分这两种方法的内容,但保留相同的REST API?
感谢您对此有所了解。
答案 0 :(得分: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();
}