我有两个Spring MVC控制器方法.两者都接收请求体中相同的数据(在HTLM的格式POST形式:version=3&name=product1&id=2),但一个方法处理PUT请求和另一DELETE:
@RequestMapping(value = "ajax/products/{id}", method = RequestMethod.PUT)
@ResponseBody
public MyResponse updateProduct(Product product, @PathVariable("id") int productId) {
//...
}
@RequestMapping(value = "ajax/products/{id}", method = RequestMethod.DELETE)
@ResponseBody
public MyResponse updateProduct(Product product, @PathVariable("id") int productId) {
//...
}
Run Code Online (Sandbox Code Playgroud)
在第一种方法中,product参数的所有字段都已正确初始化.在第二个中,仅id初始化字段.其他字段是null或0.(id可能是因为id路径变量而初始化).
我可以看到该HttpServletRequest对象包含请求体(version=3&name=product1&id=2)中所有字段的值.它们只是没有映射到product参数的字段.
如何使第二种方法有效?
我也尝试使用带@RequestParam注释的参数.在处理PUT请求的方法中,它可以工作.在DELETE方法中,我得到一个例外:org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'version' is not present.
我需要在 …
我有以下控制器:
@RestController
public class RestaurantController {
@Autowired
RestaurantService restaurantService;
@RequestMapping(value = "/restaurant/", method = RequestMethod.GET)
public ResponseEntity<List<Restaurant>> listAllRestaurants() {
System.out.println("Fetching all restaurants");
List<Restaurant> restaurants = restaurantService.findAllRestaurants();
if(restaurants.isEmpty()){
return new ResponseEntity<List<Restaurant>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<Restaurant>>(restaurants, HttpStatus.OK);
}
@RequestMapping(value = "/restaurant/{id}", method = RequestMethod.PUT)
public ResponseEntity<Restaurant> updateRestaurant(@PathVariable("id") int id, @RequestBody Restaurant restaurant) {
System.out.println("Updating Restaurant " + id);
Restaurant currentRestaurant = restaurantService.findById(id);
if (currentRestaurant==null) {
System.out.println("Restaurant with id " + id + " not found");
return new …Run Code Online (Sandbox Code Playgroud)