2

I want to access the method only if the vegetable names are not carrot or beans or onions so if I give tomato it should return the view. I'm using the Url as below is there anything wrong in this url?

@RequestMapping("/**/vegetables/{name:^[carrot|beans|onions]}")
public String vegetablesNames(){
    return "vegetables";
}
1
  • Wouldn't it be easier to get it as @PathVariable and check inside a function? RegExp is a huge thing, I'd rather avoid them If I could. Commented Aug 10, 2017 at 7:37

1 Answer 1

4

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.

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

1 Comment

Exactly. IMHO the path should describe the general format, but contain no business (or validation) logic. The validation inside can be made with regex, comparing to a list, checked against database etc. and it will be a lot easier to change that rather than the path variable.

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.