在Spring中结合GET和POST请求方法

我有一个支持GETPOST请求的资源。 这里是一个示例资源的示例代码:

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

这两个方法中的代码实际上是相同的,除了让我们说一个variables的定义。 这两个方法可以很容易地使用method = {RequestMethod.POST, RequestMethod.GET}和一个简单的if里面。 我尝试了,但它不起作用,因为这两个方法在最后有不同的参数,即HttpServletRequestBindingResult@RequestParam是不需要的,因此在POST请求中不需要)。 任何想法如何结合这两种方法?

 @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

使用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 } 

下面是你可以做到这一点的方式之一,可能不是一个理想的做法。

有一种方法接受这两种types的请求,然后检查你收到的请求是什么types的,是“GET”还是“POST”types,一旦你知道了,做相应的操作和调用一个共同的任务都请求方法,即GET和POST。

 @RequestMapping(value = "/books") public ModelAndView listBooks(HttpServletRequest request){ //handle both get and post request here // first check request type and do respective actions needed for get and post. if(GET REQUEST){ //WORK RELATED TO GET }else if(POST REQUEST){ //WORK RELATED TO POST } commonMethod(param1, param2....); } 
 @RequestMapping(value = "/books", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter, HttpServletRequest request) throws ParseException { //your code } 

这将适用于GET和POST。

如果您的pojo(BooksFilter)必须包含您在请求参数中使用的属性,则为GET

如下所示

 public class BooksFilter{ private String parameter1; private String parameter2; //getters and setters 

URl应该如下所示

/书籍?参数1 =胡说

像这样,你可以使用它的GET和POST

Interesting Posts