在Spring中结合GET和POST请求方法 [英] Combine GET and POST request methods in Spring
问题描述
我拥有同时支持GET
和POST
请求的资源.这里是示例资源的示例代码:
I have a resource that supports both GET
and POST
requests. Here a sample code for a sample resource:
@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
轻松组合这两种方法.我试过了,但是不起作用,因为这两种方法最后都有一个不同的参数,即HttpServletRequest
和BindingResult
(@RequestParam
不是必需的,因此在POST
请求中不需要).有什么想法如何结合这两种方法吗?
The code in the two methods is practically the same, except for lets say a variable definition. The two methods can be easily combined using method = {RequestMethod.POST, RequestMethod.GET}
, and a simple if
inside. I tried, but it doesn't work, because the two methods have a different parameter at the end, i.e. HttpServletRequest
and BindingResult
(the @RequestParam
's are not required and therefore not needed in the POST
request). Any ideas how to combine the two methods?
推荐答案
@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
if @RequestParam(required = true)
then you must pass parameter1,parameter2
使用BindingResult并根据您的条件请求它们.
Use BindingResult and request them based on your conditions.
另一种方式
@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
}
这篇关于在Spring中结合GET和POST请求方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!