【问题标题】:Springboot Requestmapper RegexpressionSpring Boot 请求映射器正则表达式
【发布时间】:2020-01-19 08:10:20
【问题描述】:

在我的 Springboot-Controller 中,我的 Requestmapping 方法应该支持灵活的子目录名称。为此,我喜欢使用真正的正则表达式。我已经测试了我的正则表达式,它在 SpringBoot 和 RequestMapping 之外工作正常,但是在 RequestMapping 之上它不起作用。

如果有任何 http-requests 进入

http://dir1 或 http://dir2

我的方法 getFile 应该被调用,但它没有。

@RequestMapping(value = "{reg:\\/(dir1|dir2)+}", method = RequestMethod.GET)    
public void getFile(HttpServletResponse response, HttpServletRequest requ) throws IOException {

}

我的问题是如何做到这一点......

【问题讨论】:

  • 我猜你想恢复方法内部的路径?因此,使用@RequestMapping(value = "/{dir}", ...) public File getFile(@PathVariable("dir") String directory,...) 之类的东西可能会更好
  • 谢谢 Dirk(德语?)。我也认为我必须恢复方法内部的路径。当我写信给 Jayanthi 时,我正在寻找任何可以确认 RequestMapping 不支持通过正则表达式的多个路径值的文档行。
  • 只要您的“目录”不包含“/”,您就可以将正则表达式与 @GetMapping("/{reg:[dir1|dir2]+}") 等 PathVariable 结合使用

标签: regex spring-boot subdirectory request-mapping


【解决方案1】:

基于正则表达式的@RequestHandler可以通过(for more)实现

    @RequestMapping(value = "{reg:regexPattern}", method = RequestMethod.GET)
    public void getFile(HttpServletRequest request, HttpServletResponse response, 
            @PathVariable String reg) throws IOException {
                 ...
             }

但在您的情况下,正则表达式模式是一个包含 Slash("/") 的目录值,这使得请求处理程序难以找到确切的映射。你可以用@RequestParam代替@PathVariable


    @RequestMapping(value = "\", method = RequestMethod.GET)
    public void getFile(HttpServletRequest request, HttpServletResponse response, 
          @RequestParam("dir") String dir) throws IOException {
        ...
    }

【讨论】:

  • 感谢您的回答,但就我而言,这并没有真正帮助我,而请求是修复的,无法传输任何参数。我没有阅读任何文档中的任何行,正则表达式不支持我的子目录路径问题。
  • @LikeTomAndJerry 在你的情况下是 @GetMapping("/{reg:[dir1|dir2]+}") 结合 @PathVariable String reg
【解决方案2】:

解决方案是(Dirk Deyne 给了我提示)斜杠必须在正则表达式之外。这是解决方案,我用另一个子目录 filedir 扩展了该值以使其更清晰:

@RequestMapping(value = "/{subdir:[dir1|dir2]+}/filedir", method = RequestMethod.GET)
public void getFile(HttpServletResponse response, HttpServletRequest requ) {
  ...
}

这将处理以下传入请求:

谢谢!

【讨论】:

    猜你喜欢
    • 2020-07-15
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2019-11-25
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多