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?

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
@RequestMapping({"/", "/{page:(?!resources).*$}/**"}) is matching multilevel path after /myapp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.