You should validate inside the method:
@RequestMapping("/vegetables/{name}")
public String vegetablesNames(@PathVariable String name){
if (name.matches("your regex") {
throw new RuntimeException(name + " doesn't match");
}
return "vegetables";
}
@PathVarialbe is the variable extracted from the request URI. You can extract it and play with it as you wish.
Basically the path should describe the resource that is available at that uri. If the resource isn't available, the response should be e.g. NOT_FOUND. In Spring, default response to the request which caused RuntimeException is 5xx which isn't good choice in this case, but this is just an example.
If you're interested in handling Exceptions in Spring, just ask for clarification.