错误400 - 错误请求

时间:2017-03-14 13:16:21

标签: java spring spring-mvc

我有一个基于Spring Web模型 - 视图 - 控制器(MVC)框架的项目。 Spring Web模型 - 视图 - 控制器(MVC)框架的版本是3.2.8

我有这个控制器

@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 {

..
}

此网址的一切正常:/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)放入,但我收到了编译错误:The attribute required is undefined for the annotation type PathVariable

2 个答案:

答案 0 :(得分:1)

这是因为服务始终在等待路径变量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

答案 1 :(得分:0)

如果您不总是需要productId。尝试使用查询参数并使其可选。 required=false

此网址现在看起来像:

  1. http://localhost:8080/books/store/product?productId=232
  2. http://localhost:8080/books/store/product
  3. 像这样:

    @SuppressWarnings("unchecked")
        @RequestMapping(value = { "/books/store/product",
                       }, method = { RequestMethod.POST })
        public String saveProduct(@ModelAttribute("productForm") ProductForm productForm,
     @RequestParam(value = "productId", required = false) Long productId,
                HttpServletRequest request, Model model) throws Exception {
    
    ..
    }
    

    希望它有所帮助。