我有一个基于 Spring Web 模型- View - Controller (MVC) 框架的项目。 Spring Web模型- View - Controller (MVC)框架的版本是3.2.8
我有这个 Controller
@SuppressWarnings("unchecked")
@RequestMapping(value = { "/books/store/product",
"/books/store/product/",
"/books/store/product/{productId}",
"/books/store/product/{productId}/" }, method = { RequestMethod.POST })
public String saveProduct(@ModelAttribute("productForm") ProductForm productForm,
@PathVariable Long productId,
HttpServletRequest request, Model model) throws Exception {
..
}
此 URL 一切正常:/books/store/product/232
但是对于这个/books/store/product/
我收到此错误:
错误 400——错误请求
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.1 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
我尝试放置此@PathVariable(required = false)
,但出现编译错误:注释类型 PathVariable 所需的属性未定义
最佳答案
这是因为服务始终在等待路径变量productId
因为您使用的是 Spring 3,所以我建议您创建 2 个方法。一个带有路径变量,另一个不带路径变量。
@RequestMapping(value = { "/books/store/product",
"/books/store/product/"}, method = { RequestMethod.POST })
public String saveProduct(@ModelAttribute("productForm") ProductForm productForm,
HttpServletRequest request, Model model) throws Exception {
..
}
@RequestMapping(value = { "/books/store/product/{productId}",
"/books/store/product/{productId}/" }, method = { RequestMethod.POST })
public String saveProduct(@ModelAttribute("productForm") ProductForm productForm,
@PathVariable Long productId,
HttpServletRequest request, Model model) throws Exception {
..
}
如果您使用 Spring 4 和 Java 8,我建议您使用可选。
@PathVariable Optional<Long> productId
关于java - 错误 400——错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42787067/