Struts 2 Url Validator
The URLValidator of Struts 2 Framework checks whether
the String contained within the given field is a valid URL or not. If the
entered value is not
a valid URL, it generates an error message.
The error message is supplied
between the <message> </message> tag. The following example demonstrates
how to use the URL validator.
Follow the steps to develop the URL validator example:
Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here --> <!-- Url validation --> <action name="urlValidation"> <result>/pages/urlInputForm.jsp</result> </action> <action name="urlValidation1" class="net.roseindia.urlVaLidationAction"> <result name="input">/pages/urlInputForm.jsp</result> <result name="error">/pages/urlInputForm.jsp</result> <result>/pages/urlSuccess.jsp</result> </action> <!-- Add actions here --> </package> <!-- Add packages here --> </struts> |
Step 2 : Create an input jsp form.
urlInputForm.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
|
Step 3 : Create an Action class.
urlVaLidationAction.java
package net.roseindia;
|
Step 4 : Create an URL validator as shown:
The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.
URL validator: This Field Validator checks
whether a
given field contains a valid URL String or not. If
the entered text is
valid then you get the urlSuccess.jsp
page. Otherwise, it displays the message given in the xml file (like
"Please enter
a valid URL.").
The URL validator
takes the following parameters:
- fieldName - It refers to the field name, the URL validator is
validating.
It is required if using Plain-Validator Syntax
urlVaLidationAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
|
When the correct URL is entered the user gets the urlSuccess.jsp page displaying the entered URL.
urlSuccess.jsp
<%@page language="java" %>
|
Output:
When this application executes initially the user gets the following:
If the user enters the wrong URL then he gets:
Again, the user enters the wrong URL then he gets:
If the user enters the correct URL as
then he gets a success message as an output: