0

I am using @ParamValue annotation in my controller (Spring MVC).
Say My valid URL's are:

www.temp.com/test/a,

www.temp.com/test/b and

www.temp.com/test/c

So, my RequestMapping is:

@RequestMapping(value = "/test/{value}", method = RequestMethod.GET)

Now, my problem is that if anyone types a wrong URL like this :

www.temp.com/test/youarebroken

then I have to manually handle such a case in my controller to show 404 or not found.
Isn't there something inbuilt that sends a "not found or 404" notification to server that I can use directly ?

iAmLearning
  • 1,153
  • 3
  • 15
  • 28
  • That URL fits your pattern. Either make your pattern more restrictive or handle the error case. How could a platform know, by default, that a URL is invalid? – Sotirios Delimanolis Dec 12 '14 at 16:10
  • possible duplicate of [Trigger 404 in Spring-MVC controller?](http://stackoverflow.com/questions/2066946/trigger-404-in-spring-mvc-controller) – Nick Humrich Dec 12 '14 at 19:37

2 Answers2

0

The simplest solution is to define a custom exception handler and to throw the custom exception when a validation fails within your controller. That would require that you manage the conditions manually as you stated you do not want to do.

A different solution is to use a global exception handler and define it to deal with the HTTP errors that are handled by Spring built-in.

In this link you can see both approaches: http://www.journaldev.com/2651/spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example

However, from your question I understand you would like to return automatically an exception when certain condition in your param value does not meet, and you do not want to validate this manually within your controller. For this, you can add custom validation for an specific class and then set @Valid before the @ParamValue.

You can check this link for DataBinding http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

And this link for specific validation on param attributes: Spring Web MVC - validate individual request params

So, in plain a solution would be to define a custom validator that throws a custom exception when fails. To set @Valid for the parameters (check link) and to adjust the custom exception to handle HTTP errors (e.g. HttpStatus.NOT_FOUND).

Community
  • 1
  • 1
Javierfdr
  • 1,122
  • 1
  • 14
  • 22
0

You can use a regex in your @RequestMapping URL. Example:

@RequestMapping(value = "/test/{value:[a-z]}", method = RequestMethod.GET)

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152