5

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

MrNVK
  • 350
  • 3
  • 16

2 Answers2

6

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";
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
3

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";
}
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
shabinjo
  • 1,473
  • 1
  • 16
  • 22