简体   繁体   中英

Java Url Validation With Placeholders

I have built an API where you can register a callback URL.

The URL's are validated using the Apache UrlValidator class.

I now have to add a feature that allow to add placeholders in the configured URL.

https:/foo.com/${placeholder1}/bar/${placeholder2}

These placeholders will be dynamically replaced using the Apache StrSubstitutor or something similar.

Now my issue, how do I validate the URL's with the placeholders ?

I have thought of a solution :

  • I replace the expected placeholders with an example value
  • Then I Validate the URL using the Apache UrlValidator

My issue with this solution is that the Apache UrlValidator only returns a boolean so the error message will be quite ambiguous.

Is there another solution than creating my own regex ?

Update : following discussions in the comments

There is a finite number of allowed placeholders.

The format of the Strings that will replace the placeholders is also known.

The first objective is to be able to check if the given URL which eventually contains placeholders is valid at the time it is configured.

The second objective is, if the URL is not valid return an intelligible error message.

There are multiple error cases :

  • A placeholder used in the URL is not in the allowed placeholder list
  • The URL in not valid independently of the placeholders

For a minimal URL validation, you could use the java.net.URL constructor (it will work with your https:/foo.com/${placeholder1}/bar/${placeholder2} example).

According to the docs , it throws:

MalformedURLException - if no protocol is specified, or an unknown protocol is found, or spec is null.

You can then leverage the URL methods as a bonus, to get parts of it such as path, protocol, etc.

I would definitely advise against re-inventing the wheel with regex for URL validation.

Note that java.net.URI has a much stricter validation and would fail your example with placeholders as is.

Edit

As discussed, since you need to validate placeholders as well, you probably want to actually try to fill them first and fail fast if something's wrong, then proceed and validate the populated URL against java.net.URI , for strict validation.

General caveat

You might also want to make your life easier and leverage an existing framework that would allow you to use annotated path variables in the first place (eg Spring , etc.), but that's quite a broad discussion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM