Search code examples
springspring-mvcrequest-mappinghttp-verbs

Combine GET and POST request methods in Spring


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
}

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?


Solution

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

    if @RequestParam(required = true) then you must pass parameter1,parameter2

    Use BindingResult and request them based on your conditions.

    The Other way

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