MrNVK
MrNVK

Reputation: 372

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 /.

Upvotes: 6

Views: 8713

Answers (2)

anubhava
anubhava

Reputation: 785256

Above answer didn't really work for me. As per official Spring doc it should be done like this:

@RequestMapping(value = "{*path}", method = RequestMethod.GET)
@ResponseBody
public String handleAll(@PathVariable(value = "path") String path) {
    log.debug("Requested path is: {}", path);
    return "forward:/static/index.html";
}

Upvotes: 8

shabinjo
shabinjo

Reputation: 1561

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";
}
}

Upvotes: 4

Related Questions