java - 错误 400——错误请求

标签 java spring spring-mvc

我有一个基于 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/

相关文章:

java - 如何使用 RedirectAttributes 在另一个 Controller 中调用一个 Controller 方法

java - 从包含多个内容的代码库启动特定的 Spring Boot 服务

java - 如果满足某些条件,如何在启动过程中退出spring应用程序?

java - SinglyLinkedList 中头之后的下一个节点出现 NullPointerException

spring - Spring Data JPA中@Modifying方法的返回值是什么意思

java - Spring 处理程序拦截器 : how to access class annotations?

java - activemq-all.jar (5.14.0) 不适用于 Spring 4.3.6?

java - 尝试将数据添加到数据库时出现未知列

java - false 和 Boolean.FALSE 有什么区别?

java - 将另一个类添加到现有类中