1

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?

1
  • 1
    You can apply interceptor logic. Commented Jul 16, 2020 at 8:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect!!! Sorry resources was just one of the examples for me really. My main point was how to apply regex to the mapping value as title suggested and I just used resources as what I thought a valid example. Your answer helped me with everything and blew me out of the water!!! Love it! Thanks :)

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.