1

I need a quick help regarding validation check in Spring MVC. I have a basic HTML form not the JSTL Tag form. How do I check or implement a straight forward data validation check in Spring MVC? One way in my mind coming right now is to use regex to verify the user name is alphanumeric [a-zA-Z0-9].

But I have seen people use Validator do this job. I want to use Validator as it seems more profession.

Second question,

I'm trying to get a Exception handling working properly but it is not working. I want the absolute basic response to happen, the response throws a HTTP.404 response. My simple method:

 @RequestMapping(value="/request/view/{id}",method=RequestMethod.GET)
    public String requestSubmit(Model model)

Now with my response String, how can I do it? After search on Stackoverflow. They said to create a generic class such as NotFoundException and extend it RunTimeException. But I still don't know how to I set the response intentionally to be 404 or any other response actually, even Http.BANDWIDTH_EXCEEEDED_RESPONSE

devyJava
  • 135
  • 8
  • 1
    Regarding the validation you may give a look [here](https://www.baeldung.com/spring-mvc-custom-validator); regarding to your second question i didn't understand it properly – Angelo Immediata Mar 20 '19 at 08:05
  • Please clarify your use case. What your `requestSublit` method should do? What does `Model` object contain? – da-sha1 Mar 20 '19 at 09:07
  • @AngeloImmediata I have the usual method in Spring MVC which return a view as 'String' Everything is fine and normal. But in certain cases, say when the user tries to enter a page not authorized to her, I want to throw a `404` or access denied page. How can I do it? Do I need to create my own set of HTTP failure pages? I don't know how to return it as a view. Its described here, the ResponseEntity is not working for me https://stackoverflow.com/questions/16232833/how-to-respond-with-http-400-error-in-a-spring-mvc-responsebody-method-returnin – devyJava Mar 20 '19 at 14:34

1 Answers1

1

Fist thing you should know: it's better to use POST instead of GET in form submitting. Because when you use GET, all your model properties sent as url parameter and it's not a good practice.

For using validation, you can use @Valid as this:

public String requestSubmit(@Valid Model model)

Then you can use validation annotation like @NotNull, @Size, ... at every property of Model class you want to validate it.

When a user submits your form, if every form attribute has validation problem, spring throws MethodArgumentNotValidException automatically. For getting validation errors, you can use try-catch block in your controller or better way is to have central exception handler with @ControllerAdvice.

hamed
  • 7,939
  • 15
  • 60
  • 114