unit 5
unit 5
Advance Java
XML
XML stands for extensible markup language. A markup language is a set of codes, or
tags, that describes the text in a digital document. The most famous markup language is
hypertext markup language (HTML), which is used to format Web pages.
USE OF XML
XML has a variety of uses for Web, e-business, and portable applications.
The following are some of the many applications for which XML is useful:
1. Web publishing: XML allows you to create interactive pages, allows the customer
to customize those pages, and makes creating e-commerce applications more
intuitive. With XML, you store the data once and then render that content for
different viewers or devices based on style sheet processing using an Extensible
Style Language (XSL)/XSL Transformation (XSLT) processor.
2. Web searching and automating Web tasks: XML defines the type of information
contained in a document, making it easier to return useful results when searching
the Web: For example, using HTML to search for books authored by Tom Brown
is likely to return instances of the term 'brown' outside of the context of author.
Using XML restricts the search to the correct context (for example, the
information contained in the <author> tag) and returns only the information that
you want. By using XML, Web agents and robots (programs that automate Web
searches or other tasks) are more efficient and produce more useful results.
The XML prolog is optional. If it exists, it must come first in the document.
XML documents can contain international characters, like Norwegian øæå or French êèé.
To avoid errors, you should specify the encoding used, or save your XML files as UTF-8.
UTF-8 is also the default encoding for HTML5, CSS, JavaScript, PHP, and SQL.
<p>This is a paragraph.</p>
<br />
Note: The XML prolog does not have a closing tag! This is not an error. The prolog is not a part
of the XML document.
Opening and closing tags must be written with the same case:
<message>This is correct</message>
"Opening and closing tags" are often referred to as "Start and end tags". Use whatever you
prefer. It is exactly the same thing.
In the example above, "Properly nested" simply means that since the <i> element is opened
inside the <b> element, it must be closed inside the <b> element.
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error because the
parser interprets it as the start of a new element.
To avoid this error, replace the "<" character with an entity reference:
Only < and & are strictly illegal in XML, but it is a good habit to replace > with > as well.
Comments in XML
The syntax for writing comments in XML is similar to that of HTML:
STRUTS
o Model: It represents the business layer of application. It is an object to carry the data that can
also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data that the
model contains.
o Controller: It works on both the model and view. It is used to manage the flow of application,
i.e. data flow in the model object and to update the view whenever data is changed.
In Java Programming, the Model contains the simple Java classes, the View used to display the data and
the Controller contains the servlets. Due to this separation the user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
View Layer
As the name depicts, view represents the visualization of data received from the
model. The view layer consists of output of application or user interface. It sends
the requested data to the client, that is fetched from model layer by controller.
Let's take an example where we create a view using the EmployeeView class.
EmployeeView.java
1. // class which represents the view
2. public class EmployeeView {
3.
4. // method to display the Employee details
5. public void printEmployeeDetails (String EmployeeName, String EmployeeId, String EmployeeDepartment){
6. System.out.println("Employee Details: ");
7. System.out.println("Name: " + EmployeeName);
8. System.out.println("Employee ID: " + EmployeeId);
9. System.out.println("Employee Department: " + EmployeeDepartment);
10. }
11. }
Controller Layer
The controller layer gets the user requests from the view layer and processes them, with the necessary
validations. It acts as an interface between Model and View. The requests are then sent to model for data
processing. Once they are processed, the data is sent back to the controller and then displayed on the
view.
Let's consider the following code snippet that creates the controller using the EmployeeController class.
EmployeeController.java
1. class which represent the controller
2. public class EmployeeController {
3.
4. // declaring the variables model and view
5. private Employee model;
6. private EmployeeView view;
7.
8. // constructor to initialize
9. public EmployeeController(Employee model, EmployeeView view) {
10. this.model = model;
11. this.view = view;
12. }
13.
14. // getter and setter methods
15. public void setEmployeeName(String name){
16. model.setName(name);
17. }
18.
19. public String getEmployeeName(){
20. return model.getName();
21. }
22.
23. public void setEmployeeId(String id){
24. model.setId(id);
25. }
26.
27. public String getEmployeeId(){
28. return model.getId();
29. }
30.
31. public void setEmployeeDepartment(String Department){
32. model.setDepartment(Department);
33. }
34.
35. public String getEmployeeDepartment(){
36. return model.getDepartment();
37. }
38.
39. // method to update view
40. public void updateView() {
41. view.printEmployeeDetails(model.getName(), model.getId(), model.getDepartment());
42. }
43. }
STRUTS FRAMEWORK
So far, we know how to make a web app using servlet classes and JSP files, and
we know how to use libaries in our code. We’ve built our web apps using the
following approach:
What’s a Framework?
A software framework is code that was written by other people, that you can use
to help organize your own code. If you think that sounds similar to a software
library, you aren’t wrong! There is a blurry line between what counts as a
framework versus what counts as a library, but the way I look at it is:
Download Struts
Go to the Struts download page and download the latest version of Struts. You
only need the “Essential Dependencies” version. That gives you a .zip file, which
you can unzip anywhere. (I put mine on my desktop for now.)
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<filter>
<filter-name>struts2</filter-name>
<filter-
class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</fil
ter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
This sets up a filter that sends every URL to the Struts framework. This is how
Struts “sits between” the server and your code. Now when the server receives a
request, it will send that request to Struts, and Struts will then send it to our
action classes, which we’ll talk about… right now.
import com.opensymphony.xwork2.ActionSupport;
@Override
public String execute(){
messageToDisplay = "Happy coding!";
return ActionSupport.SUCCESS;
}
This class extends the ActionSupport class, similar to how a servlet extends
the HttpServlet class. It overrides the execute() function, which Struts
automatically calls when it receives a request. This function contains any
“business logic” required to fulfill a request, and it returns a String value. In this
case, it returns the predefined ActionSupport.SUCCESS value, which behind the
scenes is a value of "success" but could be anything you want. This helps Struts
know which view to show, which we’ll see in a second.
This also defines a getMessage() function, which you can use from a JSP view.
More on that in a second.
It’s also worth noting that with a servlet class, you only ever have one instance of
a class, which is called from multiple threads. But in Struts, a new instance of
your action class is created for every request. (Hint: try to add
a visitCount variable to your action class that you increment every time the page
is loaded.)
hello.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<title>Hello World Struts</title>
</head>
<body>
<h1>Hello World</h1>
<p><s:property value="message" /></p>
</body>
</html>
Hopefully you’re already familiar with JSP (if not check out the JSP tutorial), but
this code contains a couple new things:
First, the <%@ taglib prefix="s" uri="/struts-tags"%> line imports the Struts
taglib, which gives us extra Struts functionality in JSP. We then use that taglib in
the <s:property value="message" /> line. This property tag looks for a function
named getXYZ(), where XYZ is whatever you supply in the value attribute. In other
words, this tag ends up calling the getMessage() function in our action class. This
allows us to separate our logic from our view, while still easily passing data to be
rendered.
There are a bunch of other Struts tags you can use in your JSP files. Read more
about them here.
The struts.xml file needs to be in the same directory as your code, not in the top
of the WEB-INF folder! So if you’re using the console to compile everything, it
should be in the classes directory; and if you’re using Eclipse then it should be in
the src directory.
Run the Web App
Now we should be able to run our web app just like we’ve been running all of our
other web apps. If you’re using the console, then copy the web app directory into
the Jetty folder. If you’re using Eclipse, then just push the run button.
Struts features
In the previous tutorials we covered how to configure Struts to map a URL such as hello.action to an
Action class such as HelloWorldAction (specifically the execute method).
Action Mapping
The Action mapping above also specified that if the execute method of
class HelloWorldAction returns success then the view HelloWorld.jsp will be returned to the browser.
This tutorial will introduce you to the basics of writing the controller logic in the Action class.
Struts 2 Action classes usually extend the ActionSupport class, which is provided by the Struts 2
framework. Class ActionSupport provides default implementations for the most common actions (e.g.
execute, input) and also implements several useful Struts 2 interfaces. When your Action class extends
class ActionSupport your class can either override the default implementations or inherit them.
If you examine class HelloWorldAction from tutorial Using Struts 2 Tags you’ll see that it extends the
class ActionSupport and then overrides method execute.
The method execute is where we placed what we want this controller to do in response to
the hello.action.
helloCount++;
return SUCCESS;
}
Note that method execute declares it throws an Exception. We’ll cover in a later tutorial how to configure
Struts to handle any Exceptions thrown from the Action classes methods.
In the Using Struts 2 Tags example application we added a Struts 2 form to index.jsp.
<s:form action="hello">
<s:textfield name="userName" label="Your name" />
<s:submit value="Submit" />
</s:form>
Make a note of the value of the name attribute for the Struts 2 textfield tag, which is userName. When the
user clicks on the submit button for the above form, the action hello will be executed (hello.action). The
form field values will be posted to the Struts 2 Action class (HelloWorldAction). The Action class may
automatically receive those form field values provided it has a public set method that matches the form
field name value.
So for the HelloWorldAction class to automatically receive the userName value it must have a public
method setUserName (note the JavaBean convention discussed in tutorial Hello World).
For the example application associated with this tutorial, add the following Java code to
class HelloWorldAction.
Add userName to HelloWorldAction
To personalize the MessageStore message (recall that class MessageStore is storing the message to
display) add the following Java code to the HelloWorldAction’s execute method after the statement that
instantiates the MessageStore object.
if (userName != null) {
messageStore.setMessage( messageStore.getMessage() + " " + userName);
}
Now build and run (mvn jetty:run) the application. Enter your name in the form and click the submit
button. You should see the following page.
When the form is submitted, Struts will call any set methods of the HelloWorldAction class that match the
form field names. So in this example method setUserName was called and passed the value the user
entered in the userName form field.
On the index.jsp we also have a Struts 2 action link (see tutorial Using Struts 2 Tags) that includes a
query string parameter: userName=Bruce+Phillips. If you click on that link you should see the following
result:
Since the query string parameter is userName, Struts passed the value of that parameter to
the setUserName method.
On the view page, HelloWorld.jsp, you can also access the userName value by using the Struts 2 property
tag (see tutorial Using Struts 2 Tags). Try showing just the userName value on the view page.
The above example introduced you to how to code the Action class so it can process user input on a form
or values in a query string parameter. If the form had numerous fields, it would be cumbersome to have a
set method that matches up with each form field. So next how to integrate a model class, form fields in
the view and form processing in the Action class.
To encapsulate this data, we’ll use a simple Java class that follows the basic Java Bean specifications
(public set/get methods for each instance field). If you’re following along add this class to the
package org.apache.struts.register.model in the Coding Struts 2 Actions example.
Person.java
Form structure
To collect the above information we’ll use a Struts 2 form. When creating this form the key concept we
need to employ is to tie each form field to a specific instance field of an object of type Person. Let’s look
over the form first and then discuss some key points. Create a view page
named register.jsp (in src/main/webapp)
register.jsp
<s:form action="register">
<s:textfield name="personBean.firstName" label="First name" />
<s:textfield name="personBean.lastName" label="Last name" />
<s:textfield name="personBean.email" label ="Email"/>
<s:textfield name="personBean.age" label="Age" />
<s:submit/>
</s:form>
</body>
</html>
Since we are using Struts 2 tags, at the top of the page we need the Struts tag library declaration.
The Struts 2 form will submit to an action named register. We’ll need to define that action in
our struts.xml file.
Note the four Struts 2 textfield tags. Each tag has a name value that includes an attribute of
the Person class (e.g. firstName). The name attribute’s value also has a reference to an object
called personBean. This object is of type Person. When we create the Action class that handles this form
submission, we’ll have to specify that object in that Action class (see below).
The complete name value, personBean.firstName, instructs Struts 2 to use the input value for that
textfield as the argument to the personBean object’s setFirstName method. So if the user types “Bruce” in
the textfield that has the label “First name”, the personBean’s firstName instance field will have a value of
“Bruce”.
Note that we have a Struts 2 textfield for each instance field of the class Person. Remember that Person
class’s age attribute is of type integer. All form field input values are Strings. Struts 2 will automatically
convert the String value (“25”) the user entered for the age form field to 25 when calling
the setAge method of object personBean.
Here is the Action class used for this example. Place it in package org.apache.struts.register.action.
package org.apache.struts.register.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts.register.model.Person;
return SUCCESS;
}
In the Register class note that we’ve declared an attribute named personBean of type Person and there is
a public get and set method for this object.
The Register class also overrides the execute method. The execute method is the one we will specify in
the struts.xml to be called in response to the register action. In this example, the execute method just
returns the String constant SUCCESS (inherited from the ActionSupport class). But in a real application,
within the execute method we would call upon other classes (Service objects) to perform the business
processing of the form, such as storing the user’s input into a data repository.
The personBean object of type Person declared in the Register Action class matches the personBean name
we used in the form’s textfields. When the form is submitted, the Struts 2 framework will inspect the
Action class and look for an object named personBean. It will create that object using the Person class’s
default constructor. Then for each form field that has a name value of personBean.someAttribute
(e.g personBean.firstName) it will call the personBean’s public set method for that attribute and pass it the
form field’s value (the user input). This all happens before the execute method occurs.
When Struts 2 runs the execute method of class Register, the personBean object in class Register now
has values for its instance fields that are equal to the values the user entered into the corresponding form
fields.
By using a Java model class to encapsulate the data provided by the form we don’t have to have a
separate attribute (with public set/get methods) in the Action class (Register) for each form field.
thankyou.jsp
If you don’t recall how the Struts 2 property and url tags work consult the Using Struts 2 Tags tutorial.
The above action tells Struts 2 that when the register action is provided to call method execute of
class Register. If that method returns result “success” return to the browser the thankyou.jsp.
Note that we don’t need to tell Struts 2 anything about processing the form. The transfer of the form field
input values to the personBean object will happen automatically provided we’ve followed the convention of
naming our form fields to match personBean.attributeName (e.g. personBean.lastName).
Link to register.jsp
Fill out the form and click the submit button. You should then see the thankyou.jsp page.
If you recall from the Processing Forms tutorial the user’s input into the form fields is placed by Struts 2
into the Java model class personBean. So a user’s input into the firstName field would end up as the value
for personBean’s firstName instance field (via the personBean.setFirstName method).
In the validate method we can refer to get the values of personBean’s instance fields by using the
appropriate get methods. Once we have the values we can employ logic to enforce our business rules.
validate method
if (personBean.getEmail().length() == 0) {
addFieldError("personBean.email", "Email is required.");
}
When the user presses the submit button on the register form, Struts 2 will transfer the user’s input to the
personBean’s instance fields. Then Struts 2 will automatically execute the validate method. If any of the if
statements are true, Struts 2 will call its addFieldError method (which our Action class inherited by
extending ActionSupport).
If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts
2 framework will return input as the result of calling the action.
To handle the return value of input we need to add the following result to our action node in struts.xml.
<result name="input">/register.jsp</result>
The above result node goes just after the success result node for the register action and before the
closing of the action node.
Error Messages
So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp.
Since we used Struts 2 form tags, automatically Struts 2 will add the error messages. These error
messages are the ones we specified in the addFieldError method call. The addFieldError method takes
two arguments. The first is the form field name to which the error applies and the second is the error
message to display above that form field.
will cause the message First name is required to be displayed above the firstName field on the form.
If you have made the above changes to the Processing Forms tutorial or you have downloaded
from form-validation run the application (see the README.txt in the project root folder). Click on the
Please register link. On the registration form, just click the submit button and you should see:
Struts 2 called the validate method, validation failed, the register.jsp was displayed with the error
messages.
Struts 2 validation is configured via XML or annotations. Manual validation in the action is also possible,
and may be combined with XML and annotation-driven validation.
Validation also depends on both the validation and workflow interceptors (both are included in the
default interceptor stack). The validation interceptor does the validation itself and creates a list of field-
specific errors. The workflow interceptor checks for the presence of validation errors: if any are found, it
returns the “input” result (by default), taking the user back to the form which contained the validation
errors.
If we’re using the default settings and our action does not have an “input” result defined and there are
validation (or, incidentally, type conversion) errors, we’ll get an error message back telling us there’s no
“input” result defined for the action.
Using Annotations
Annotations can be used as an alternative to XML for validation.
Bean Validation
With struts 2.5 comes the Bean Validation Plugin. That is an alternative to the classic struts validation
described here. See the Plugin Page for details.
Examples
In all examples given here, the validation message displayed is given in plain English - to internationalize
the message, put the string in a properties file and use a property key instead, specified by the ‘key’
attribute. It will be looked up by the framework (see Localization).
1. Basic Validation
2. Client-side Validation
3. AJAX Validation
4. Using Field Validators
5. Using Non Field Validators
6. Using Visitor Field Validator
7. How do we repopulate controls when validation fails (FAQ entry)
Bundled Validators
When using a Field Validator, Field Validator Syntax is ALWAYS preferable than using the Plain Validator
Syntax as it facilitates grouping of field-validators according to fields. This is very handy especially if a
field needs to have many field-validators which is almost always the case.
1. conversion validator
2. date validator
3. double validator
4. email validator
5. expression validator
6. fieldexpression validator
7. int validator
8. regex validator
9. required validator
10. requiredstring validator
11. short validator
12. stringlength validator
13. url validator
14. visitor validator
15. conditional visitor validator
Registering Validators
Validation rules are handled by validators, which must be registered with the
ValidatorFactory (using the registerValidator method). The simplest way to do so is to
add a file name validators.xml in the root of the classpath (/WEB-INF/classes) that
declares all the validators you intend to use.
List of validators
validators>
<validator name="required"
class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring"
class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int"
class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long"
class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short"
class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double"
class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date"
class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression"
class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression"
class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email"
class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="creditcard"
class="com.opensymphony.xwork2.validator.validators.CreditCardValidator"/>
<validator name="url"
class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor"
class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion"
class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength"
class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex"
class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor"
class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"
/>
</validator
Turning on Validation
The default interceptor stack, “defaultStack”, already has validation turned on. When creating your own
interceptor-stack be sure to include both the validation and workflow interceptors. From struts-
default.xml:
<interceptor-stack name="defaultStack">
...
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
<interceptor name="validation"
class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
This interceptor allows us to turn off validation for a specific method by using
the @org.apache.struts2.interceptor.validation.SkipValidation annotation on the action method.
Validator Scopes
Field validators, as the name indicate, act on single fields accessible through an action. A validator, in
contrast, is more generic and can do validations in the full action context, involving more than one field (or
even no field at all) in validation rule. Most validations can be defined on per field basis. This should be
preferred over non-field validation wherever possible, as field validator messages are bound to the related
field and will be presented next to the corresponding input element in the respecting view.
Non-field validators only add action level messages. Non-field validators are mostly domain specific and
therefore offer custom implementations. The most important standard non-field validator provided by
XWork is ExpressionValidator.
Notes
Non-field validators takes precedence over field validators regardless of the order they are defined in *-
validation.xml. If a non-field validator is short-circuited, it will causes its non-field validator to not
being executed. See validation framework documentation for more info.
Here we can see the configuration of validators for the SimpleAction class. Validators (and field-
validators) must have a type attribute, which refers to a name of an Validator registered with
the ValidatorFactory as above. Validator elements may also have <param> elements with name and
value attributes to set arbitrary parameters into the Validator instance. See below for discussion of the
message element.
In this context, “Action Alias” refers to the action name as given in the Struts configuration. Often, the
name attribute matches the method name, but they may also differ.
There is another option to customise validation messages by using parametrized messages. Either you
can use them via XML or with annotations.
XML
To use this new approach you must use a proper header in a <ActionName>-validation.xml file, see
below:
<?xml version="1.0"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
...
</validators>
Now you can define validators that will use parametrized messages as below:
<field name="username">
<field-validator type="requiredstring">
<message key="errors.required">
<param name="0">getText('username.field.name')</param>
</message>
</field-validator>
</field>
NOTE: Please be aware that all the parameters will be evaluated against ValueStack, please do not
reference user controlled values or incoming parameters in request as this can lead to a security
vulnerability
Now you can define your properties file with localized messages:
errors.required={0} is required.
username.field.name=Username
As you can see you defined a errors.required key with a placeholder for the param. The names of the
params are not important, order is important as this mechanism uses MessageFormat to format the
message.
Username is required.
Annotations
Validator Flavor
The validators supplied by the XWork distribution (and any validators you might write yourself) come in
two different flavors:
Plain Validators (such as the ExpressionValidator) perform validation checks that are not inherently tied
to a single specified field. When you declare a plain Validator in your -validation.xml file you do not
associate a fieldname attribute with it. You should avoid using plain Validators within the <field-
validator> syntax described below.
FieldValidators (such as the EmailValidator) are designed to perform validation checks on a single field.
They require that you specify a fieldname attribute in your -validation.xml file. There are two different
(but equivalent) XML syntaxes you can use to declare FieldValidators (see “ vs. syntax" below).
There are two places where the differences between the two validator flavors are important to keep in
mind:
1. when choosing the xml syntax used for declaring a validator (either <validator> or <field-
validator>)
2. when using the short-circuit capability
Note that you do not declare what “flavor” of validator you are using in your -validation.xml file, you just
declare the name of the validator to use and Struts will know whether it’s a “plain Validator” or a
“FieldValidator” by looking at the validation class that the validator’s programmer chose to implement.
1. <validator>
2. <field-validator>
Non-Field-Validator: The <validator> element allows you to declare both types of validators (either a
plain Validator a field-specific FieldValidator).
<validator type="expression">
<param name="expression">foo gt bar</param>
<message>foo must be great than bar.</message>
</validator>
<validator type="required">
<param name="fieldName">bar</param>
<message>You must enter a value for bar.</message>
</validator>
field-validator: The <field-validator> elements are basically the same as the <validator> elements
except that they inherit the fieldName attribute from the enclosing <field> element. FieldValidators
defined within a <field-validator> element will have their fieldName automatically filled with the value of
the parent <field> element’s fieldName attribute. The reason for this structure is to conveniently group
the validators for a particular field under one element, otherwise the fieldName attribute would have to be
repeated, over and over, for each individual <validator>.
It is always better to defined field-validator inside a <field> tag instead of using a <validator> tag and
supplying fieldName as its param as the xml code itself is clearer (grouping of field is clearer).
Note that you should only use FieldValidators (not plain Validators) within a block. A plain Validator inside
a <field> will not be allowed and would generate error when parsing the xml, as it is not allowed in the
defined DTD (xwork-validator-1.0.2.dtd)
<field name="email_address">
<field-validator type="required">
<message>You cannot leave the email address field empty.</message>
</field-validator>
<field-validator type="email">
<message>The email address you entered is not valid.</message>
</field-validator>
</field>
The choice is yours. It’s perfectly legal to only use elements without the elements and set
the fieldName attribute for each of them. The following are effectively equal:
<field name="email_address">
<field-validator type="required">
<message>You cannot leave the email address field empty.</message>
</field-validator>
<field-validator type="email">
<message>The email address you entered is not valid.</message>
</field-validator>
</field>
<validator type="required">
<param name="fieldName">email_address</param>
<message>You cannot leave the email address field empty.</message>
</validator>
<validator type="email">
<param name="fieldName">email_address</param>
<message>The email address you entered is not valid.</message>
</validator>
Short-Circuiting Validator
It is possible to short-circuit a stack of validators. Here is another sample config file containing
validation rules from the Xwork test cases: Notice that some of the <field-
validator> and <validator> elements have the short-circuit attribute set to true.
Plain validator takes precedence over field-validator. They get validated first in the order they are defined
and then the field-validator in the order they are defined. Failure of a particular validator marked as short-
circuit will prevent the evaluation of subsequent validators and an error (action error or field error
depending on the type of validator) will be added to the ValidationContext of the object being validated.
1. Plain Validator 1
2. Plain Validator 2
3. Field Validators for email field
4. Field Validators for email2 field
Since Plain Validator 2 is short-circuited, if its validation failed, it will causes Field validators for email field
and Field validators for email2 field to not be validated as well.
Usefull Information: More complicated validation should probably be done in the validate() method on
the action itself (assuming the action implements Validatable interface which ActionSupport already
does).
A plain Validator (non FieldValidator) that gets short-circuited will completely break out of the validation
stack. No other validators will be evaluated and plain validators takes precedence over field validators
meaning that they get evaluated in the order they are defined before field validators get a chance to be
evaluated.
A FieldValidator that gets short-circuited will only prevent other FieldValidators for the same field from
being evaluated. Note that this “same field” behavior applies regardless of whether
the <validator> or <field-validator> syntax was used to declare the validation rule. By way of example,
given this -validation.xml file:
<validator type="expression">
<param name="expression">foo gt bar</param>
<message>foo must be great than bar.</message>
</validator>
both validators will be run, even if the “required” validator short-circuits. “required” validators are
FieldValidator’s and will not short-circuit the plain ExpressionValidator because FieldValidators only short-
circuit other checks on that same field. Since the plain Validator is not field specific, it is not short-
circuited.
● <actionClass>-validation.xml
● <actionClass>-<actionAlias>-validation.xml
It should be noted that the nett effect will be validation on both the validators available in both validation
configuration file. For example if we have ‘requiredstring’ validators defined in both validation xml file for
field named ‘address’, we will see 2 validation error indicating that the the address cannot be empty
(assuming validation failed). This is due to WebWork will merge validators found in both validation
configuration files.
The logic behind this design decision is such that we could have common validators in <actionClass>-
validation.xml and more context specific validators to be located in <actionClass>-<actionAlias>-
validation.xml.
● com.opensymphony.xwork2.validator.validators.ValidatorSupport
● com.opensymphony.xwork2.validator.validators.FieldValidatorSupport
● com.opensymphony.xwork2.validator.validators.RangeValidatorSupport
●
com.opensymphony.xwork2.validator.validators.RepopulateConversionErrorFieldValidatorSup
port
STRUTS TILES Struts Tiles framework is a layout framework, which allow users to
maintain a standard look of header, footer and menu across all of your web pages efficiently.
5) Inherit the tiles-default package and define all the result type as tiles in struts.xml
This xml file defines one package with one action and two results.
struts.xml
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
3. "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5.
6.
7. <package name="abc" extends="tiles-default" >
8.
9. <action name="login" class="com.javatpoint.Login">
10. <result name="success" type="tiles">login-success</result>
11. <result name="error" type="tiles">login-error</result>
12. </action>
13.
14. </package>
15. </struts>
6)Create the tiles.xml file and define all the tiles definitions
The tiles.xml file must be located inside the WEB-INF directory.
tiles.xml
1. <?xml version="1.0" encoding="UTF-8" ?>
2.
3. <!DOCTYPE tiles-definitions PUBLIC
4. "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
5. "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
6.
7. <tiles-definitions>
8.
9. <definition name="login-success" template="/layoutmanager.jsp">
10. <put-attribute name="title" value="Welcome Page"/>
11. <put-attribute name="body" value="/login-success.jsp"/>
12. </definition>
13.
14. <definition name="login-error" template="/layoutmanager.jsp">
15. <put-attribute name="title" value="Login Error"/>
16. <put-attribute name="body" value="/login-error.jsp"/>
17. </definition>
18.
19. </tiles-definitions>
footer.jsp
1. <hr>
2. <h2 style="background-color:pink;text-align:center;">It is footer tile</h2>
login-success.jsp
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2.
3. Welcome, <s:property value="name"/>
4. </textrea></div>
5. <hr/>
6. <strong>login-error.jsp</strong>
7. <div class="codeblock"><textarea name="code" class="xml" >
8. Sorry, username or password error!
9. <jsp:include page="index.jsp"></jsp:include>
download this example (developed by Eclipse IDE)
download this example (developed by myeclipse IDE)
Output: