【问题标题】:Spring boot: how to match all routes?Spring Boot:如何匹配所有路由?
【发布时间】:2017-11-08 17:50:05
【问题描述】:

我正在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等一级url。我想匹配/index/some/other/staff等所有url级别。我该怎么做?

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,但我需要从/ 开始。

【问题讨论】:

  • 如果你直接请求 /static/index.html 会发生什么?
  • 我的应用程序将返回 index.html。
  • 然后尝试转发到您的应用程序的完整路径?
  • 尝试阅读这个类似的问题:stackoverflow.com/questions/12569308/…
  • @AmerQarabsa,对不起,我不完全明白我需要做什么:)

标签: java spring spring-boot


【解决方案1】:

上面的答案对我来说真的不起作用。根据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";
}

【讨论】:

    【解决方案2】:

    你可以试试这个:

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

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多