Search code examples
javaregexspring-mvcrequest-mapping

Regex to match empty or any string except a specific string for request mapping


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?


Solution

  • 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
        }
    }