Spring boot:如何匹配所有路由?

时间:2017-06-07 11:37:28

标签: java spring spring-boot

我正在Spring boot 1.5.3开发一个简单的Web应用程序,我需要所有路由来发送静态index.html文件。现在,我有这个:

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

我的应用程序仅包含静态资源和REST API。但问题是上面显示的控制器只匹配第一级网址,如/index/department等。我想匹配所有网址级别,如/index/some/other/staff等。我该怎么做?

PS。我已尝试在/**中使用模板@RequestMapping,但我的应用程序已因StackOverflow错误而崩溃。

更新

如果再向url添加一个级别,则所有级别都将按预期工作:

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

/test/test/some/other/staff的所有请求都将返回index.html,但我需要以/开头。

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

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

答案 1 :(得分:2)

以上答案对我不起作用。按照 official Spring doc 应该这样做:

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