76

我有一个支持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
}

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

4

3 回答 3

113
@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)那么你必须传递参数1,参数2

使用 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
}
于 2013-08-01T07:54:25.390 回答
9

以下是您可以实现这一目标的一种方式,可能不是理想的方式。

让一种方法接受这两种类型的请求,然后检查您收到的请求类型,是“GET”还是“POST”类型,一旦你知道了,就执行相应的操作并调用一种执行常见任务的方法两种请求方法,即 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....);
}
于 2013-08-01T07:29:06.077 回答
2
@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

这适用于 GET 和 POST。

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

像下面

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl 应该如下所示

/books?parameter1=blah

像这样你可以将它用于 GET 和 POST

于 2017-09-11T19:36:51.017 回答