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

时间:2013-08-01 07:10:17

标签: spring spring-mvc request-mapping httpverbs

我有一个支持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不是必需的,因此不需要在POST请求中。任何想法如何结合这两种方法?

3 个答案:

答案 0 :(得分:78)

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

答案 1 :(得分:7)

以下是您实现这一目标的方法之一,可能不是理想的做法。

有一种方法接受这两种类型的请求,然后检查你收到的请求类型,是“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....);
}

答案 2 :(得分:0)

@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应该如下所示

/书?参数1 =嗒嗒

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