Skip to content
Advertisement

Spring boot: how to match all routes?

I’m developing a simple web application on Spring boot 1.5.3 and I need all the routes to send static index.html file. Now, I have this:

@Controller
public class IndexController {

    @RequestMapping("/*")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}

My application contains only static assets and REST API. But the problem is that the controller shown above only matches the first-level url like /index, /department etc. I want to match all url levels like /index/some/other/staff etc. How can I do that?

PS. I’ve tried to use the template /** in @RequestMapping, but my application has broken with the StackOverflow error.

UPDATE

If add one more level to url, then all will work as expected:

@Controller
public class IndexController {

    @RequestMapping("/test/**")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}

All requests to /test, /test/some/other/staff will return index.html, but I need to start with /.

Advertisement

Answer

You can try this:

@Controller
public class IndexController {

@RequestMapping(value = "/**/{path:[^\.]*}")
public String index(final HttpServletRequest request) {
    final String url = request.getRequestURI();

    if (url.startsWith("/static")) {
        return String.format("forward:/%s", url);
    }

    return "forward:/static/index.html";
}
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement