Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for validating a URL with Spring-MVC?

I am using Spring MVC for my web application. I need to validate that the URL the user inputs is valid and was wondering if there is something in Spring that can do the basic checks for me (for example starts with http/https, has domain name etc).

ValidationUtils only contains very basic checks and I know I can write a regular expression in the validate() method however prefer to avoid it inm case someone has already done it :)

Thanks

like image 501
Joly Avatar asked Jan 24 '12 15:01

Joly


People also ask

Does Spring MVC provide validation support?

Spring also provides @Validator annotation and BindingResult class through which we can get the errors raised by Validator implementation in the controller request handler method.

How do you validate a request in Spring?

Validate Request parameter When creating a route with Spring, adding an annotation rule to validate the input is possible. In our case, we will apply a Regex the validate the format of the reservation's code. Now run the application and test with a bad reservation code. Launch the application and test.


2 Answers

In the past, I have always utilized Hibernate Validator. Simply annotate the appropriate field in your form bean with a @URL constraint.

If you've never used the ORM part of Hibernate before, don't let that scare you. The Validator portion is not dependent on the ORM stuff, and integrating it into Spring is very straightforward.

If for some reason you can't use Hibernate Validator... or you just want to stick with what you're comfortable with, a good place for regex's is RegExLib.com; several patterns that can match a URI are listed there.

like image 92
The Awnry Bear Avatar answered Oct 21 '22 14:10

The Awnry Bear


Ended up using UrlValidator from apache commons.

like image 41
Joly Avatar answered Oct 21 '22 15:10

Joly