1

I need to do a request mapping for an URL, which would match an empty string, or any string except a specific string after a forward slash character: /.

The below regex matches any string after /, and ignores the specific string "resources", but it is not matching empty string after that forward slash /.

@RequestMapping(value = "/{page:(?!resources).*$}")

Current output:

/myapp/abc - matches and handles - ok
/myapp/resoruces - matches and ignores this URL - ok
/myapp/ - not matched <<<<<< expected to match!

What is wrong with this regular expression?

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
user1614862
  • 3,701
  • 7
  • 29
  • 46

1 Answers1

2

If you're using spring 5 then use multiple mappings like this with an optional @PathVariable:

@RequestMapping({"/", "/{page:(?!resources).*$}"})
public void pageHandler(@PathVariable(name="page", required=false) String page) {
    if (StringUtils.isEmpty(page)) {
        // root
    } else {
        // process page
    }
}

If you're using Spring 4 and you can leverage Optional class of Java 8:

@RequestMapping({"/", "/{page:(?!resources).*$}"})
public void pageHandler(@PathVariable("page") Optional<String> page) {
    if (!page.isPresent()) {
        // root
    } else {
        // process page
    }
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    perfect, first option worked, but if I have multi level path after /myapp then it is not getting matched, for example /myapp/abc/report not matched, I can have any number of paths after /myapp – user1614862 Nov 12 '19 at 12:18
  • 1
    @RequestMapping({"/", "/{page:(?!resources).*$}/**"}) is matching multilevel path after /myapp – user1614862 Nov 12 '19 at 12:27