I have an application that will allow the user to enter and store (in a DB) a website URL for a company. The only requirement (as of now) beyond entry of the website URL is to validate that the URL is valid and display the URL with other company information.
The application consists of a client UI that will pass JSON objects to the server. Spring rest controllers handle the JSON request and bind via @RequestBody
to the entity for example to the Company
entity which contains the URL. I use @Valid
to validate the entity.
I know of two approaches.
- Assign the
websiteUrl
field ofCompany
a type ofString
and use@URL
(org.hibernate.validator.constraints.URL
) to enforce that the URL is valid. But if I use this approach how do I allow http AND https? Theprotocol
attribute accepts only a singleString
. - Assign the
websiteUrl
field ofCompany
a type ofjava.net.URL
. This still allows storage in the DB as a varchar. It also accurately reflects the type. But it lacks the simple annotation validation and binding fails if it the URL is invalid.
1 Answer 1
From@URL
Java Doc:
Validates the annotated string is an URL.
The parameters protocol, host and port are matched against the corresponding parts of the URL. and an additional regular expression can be specified using regexp and flags to further restrict the matching criteria.
Note: Per default the constraint validator for this constraint uses the java.net.URL constructor to validate the string. This means that a matching protocol handler needs to be available. Handlers for the following protocols are guaranteed to exist within a default JVM - http, https, ftp, file, and jar. See also the Javadoc for URL.
So, you only need to annotate the required param/attribute with @URL and nothing else. For example.
@URL
private String siteUrl;
In other words. Go option 1, because java.net.URL
is going to handle the validation for any of the default protocols supported by the JVM. It includes HTTP and HTTPS.
Later, if your business requires it, you can transform safely the String
into a java.net.URL
.
URL constraint validator: org.hibernate.validator.internal.constraintvalidators.hv.URLValidator
Explore related questions
See similar questions with these tags.