我有同时支持GET和POST请求的资源。这里是示例资源的示例代码:
GET
POST
@RequestMapping(value = "/books", method = RequestMethod.GET) public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter, two @RequestParam parameters, HttpServletRequest request) throws ParseException { LONG CODE } @RequestMapping(value = "/books", method = RequestMethod.POST) public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, BindingResult result) throws ParseException { SAME LONG CODE with a minor difference }
这两个方法中的代码实际上是相同的,只是说一个变量定义。可以使用method = {RequestMethod.POST, RequestMethod.GET}和简单的if内部将两种方法轻松组合。我试过了,但是不起作用,因为这两种方法最后都有一个不同的参数,即HttpServletRequestand BindingResult((@RequestParam不需要,因此在POST请求中也不需要)。任何想法如何结合这两种方法?
method = {RequestMethod.POST, RequestMethod.GET}
if
HttpServletRequest
BindingResult
@RequestParam
@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, @RequestParam(required = false) String parameter1, @RequestParam(required = false) String parameter2, BindingResult result, HttpServletRequest request) throws ParseException { LONG CODE and SAME LONG CODE with a minor difference }
如果这样,@RequestParam(required = true)则必须传递parameter1,parameter2
@RequestParam(required = true)
使用BindingResult并根据您的条件请求它们。
另一种方法
@RequestMapping(value = "/books", method = RequestMethod.GET) public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter, two @RequestParam parameters, HttpServletRequest request) throws ParseException { myMethod(); } @RequestMapping(value = "/books", method = RequestMethod.POST) public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, BindingResult result) throws ParseException { myMethod(); do here your minor difference } private returntype myMethod(){ LONG CODE }