Spring Controller to handle all requests that do not match other controllers

I have a series of controllers with query mappings that match specific URLs. I also want the controller to match any other URL that does not match with other controllers. Is there a way to do this in Spring MVC? For example, can I have a controller with @RequestMapping (value = "**") and change the processing order of the Spring controllers so that this controller is processed last to catch all unsurpassed requests? Or is there another way to achieve this behavior?

+4
source share
2 answers

If your base url looks like this: http: // localhost / myapp / , where myapp is your context, then myapp / a.html, myapp / b.html myapp / c.html will be mapped to the first method 3 in the next controller. But everything else will reach the last method that matches **. Note that if you put the ** associated method at the top of your controller, then the whole request will reach that method.

Then this controller will fulfill your requirement:

@Controller
@RequestMapping("/")
public class ImportController{

    @RequestMapping(value = "a.html", method = RequestMethod.GET)
    public ModelAndView getA(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("a");
        return mv;
    }

    @RequestMapping(value = "b.html", method = RequestMethod.GET)
    public ModelAndView getB(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("b");
        return mv;
    }

    @RequestMapping(value = "c.html", method = RequestMethod.GET)
    public ModelAndView getC(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("c");
        return mv;
    }

@RequestMapping(value="**",method = RequestMethod.GET)
public String getAnythingelse(){
return "redirect:/404.html";
}
+6
source
@RequestMapping (value = "/**", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<String> defaultPath() {
    LOGGER.info("Unmapped request handling!");
    return new ResponseEntity<String>("Unmapped request", HttpStatus.OK);
}

This will do the job with the correct controller matching order. It will be used when nothing matches.

+2
source

All Articles