Issue
I have a spring controller method
@GetMapping(value = {"{name}"})
public String index(ModelMap model, @PathVariable Optional<String> name)
I would like everything to go through this method except anything that contains a period. So something like /main.css
will be rejected while something like /maincss
will be allowed. Is there any way I can do that?
I understand that I can simply move all my resources file to resources path like /resources/main.css
and the problem is fixed, or I can change up the code so that I have two methods, one for /
and one for /name/{name}
. But for educational purposes I was wondering if I can have controller apply to everything except a certain regex. Like for example what if I want the controller to accept everything except a string that contains a word Norris.
Is there anyway to apply regex or some sort of rules to mapping value?
Solution
You can use the format varName:regex
(where colon ":" is the separator between the two) to indicate a regex check to be used on the variable:
@GetMapping(value = {"{name:^((?!Norris).)*$}"})
public String index(ModelMap model, @PathVariable Optional<String> name)
However, since your problem might be related to resources:
I understand that I can simply move all my resources file to resources path like /resources/main.css
You could also try to configure a ResourceHandlerRegistry
or a ResourceResolver
to exclude certain file (patterns) from being served as resources. More info regarding resource handling can be found here.
Answered By - Michiel