我有两个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.
我需要在 …
我正在尝试对请求正文进行 DELETE,但我不断收到 400(错误请求)错误。当我在 swagger/postman 中执行此操作时,它成功删除了记录。但从 Java 代码来看我无法做到这一点
外部 API 的设计方式需要 body 和 URL。它无法改变。请让我知道如何删除带有请求正文的条目
public Person delete(Person person, String url, Map<String, String> uriVariables) throws JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
CustomObjectMapper mapper = new CustomObjectMapper();
HttpEntity<Person> requestEntity = new HttpEntity<Person>(person);
try {
ResponseEntity<Person> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Person.class, uriVariables);
return responseEntity.getBody();
} catch (RestClientException e) {
System.out.println(mapper.writeValueAsString(person));
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
当出现异常时,我将获得 JSON 格式的 JSON 请求,并且在 Swagger/postman 中同样可以正常工作
我做了一些谷歌搜索,发现restTemplate在存在请求正文时存在删除问题。这篇文章没有帮助https://jira.spring.io/browse/SPR-12361有什么办法让它工作