javaspring-bootspring-mvc

Can I do one GetMapping for all pages in spring


I have a question about @GetMapping in Spring Boot.

If I have 20 static web pages as .html files. Could I use only one @GetMapping to get every single pages?

For example:

@GetMapping("/{static_webpages}")
public String getWeb() { return "{static_webpages}";}

Then, when the path becomes /page1, it will get page 1, and so on.


Solution

  • Extracting the name of the webpage from the URL.

    By adding a parameter to your method and annotating it with the @PathVariable annotation you can extract the name of the webpage.

        @GetMapping("/{static_webpage}")
        public String getWeb(@PathVariable("static_webpage") String webpage) {
            ...
        }
    

    Return the webpage instead of returning a string

    You probably don't want to return the content of the webpage in form of a string.
    By using the ModelAndView object as a return type of your method, your method will return a proper webpage.

        @GetMapping("/{static_webpage}")
        public ModelAndView getWeb(@PathVariable("static_webpage") String webpage) {
            ...
        }
    

    Now we can construct the ModelAndView object to redirect to the given webpage.

        @GetMapping("/{static_webpage}")
        public ModelAndView getWeb(@PathVariable("static_webpage") String static_webpage) {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("webpages/" + static_webpage);
            return modelAndView;
        }
    

    In this example the static webpages were saved in the resources/static/webpages directory for the sake of grouping them into one single directory.
    If you don't want to group them into one directory you would just store them at resources/static/, although you would have to be careful, because the ModelAndView object would then try to load its own rest endpoint, which would result in an error.

    [OPTIONAL] Removing the needed html extension in the url

    With the spring.mvc.view.suffix property in your application.properties you can provide a suffix, that is appended to every ModelAndView webpage you create.

    spring.mvc.view.suffix = .html
    

    This means that instead of having to access the webpage /myexamplepage.html you would only have to access /myexamplepage.

    Resources