@UrlValidator Annotation Example in Struts 2

By Arvind Rai, June 15, 2014
In this page we will learn how to use @UrlValidator to validate a field for a URL. URL is validated against a regex. Struts 2 provides the attribute where we can define our own regex and if we do not define then a default regex will be used. Find the attribute detail of @UrlValidator.

message : This attribute is required. This displays the error message.
key : This is I18 key which is obtained from property file.
type : The value of type can be like ValidatorType.FIELD enum.
urlRegex : It defines regex that will validate URL.
urlRegexExpression : It defines regex as expression that will validate URL.

Syntax
@UrlValidator(message = "Default message", key = "msg.i18n.key", shortCircuit = true)

@UrlValidator(message = "Default message", key = "msg.i18n.key", urlRegexExpression = "${urlRegex}") 
If we use neither urlRegex nor urlRegexExpression, then default regex will be used. Default regex is given as below
return "^(https?|ftp):\/\/" +
       "(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+" +
       "(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?" +
       "@)?(#?" +
       ")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*" +
       "[a-z][a-z0-9-]*[a-z0-9]" +
       "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}" +
       "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" +
       ")(:\\d+)?" +
       ")(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*" +
       "(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)" +
       "?)?)?" +
       "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?" +
       "$"; 
Now let's see how to use @UrlValidator in our class with default regex.
public class UserAction extends ActionSupport{
	private String url;
	public String execute() {
	   return SUCCESS; 
	}
	@UrlValidator(message = "Enter Valid URL")
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
} 
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us