2

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.

  1. Assign the websiteUrl field of Company a type of String 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? The protocol attribute accepts only a single String.
  2. Assign the websiteUrl field of Company a type of java.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.
asked Aug 30, 2017 at 17:41

1 Answer 1

3

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

answered Aug 31, 2017 at 8:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.