[go: up one dir, main page]

0% found this document useful (0 votes)
23 views53 pages

unit 5

Uploaded by

jainaishwarya084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views53 pages

unit 5

Uploaded by

jainaishwarya084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

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.

3. General applications: XML provides a standard method to access information,


making it easier for applications and devices of all kinds to use, store, transmit,
and display data.
4. e-business applications: XML implementations make electronic data interchange
(EDI) more accessible for information interchange, business-to-business
transactions, and business-to-consumer transactions.
5. Metadata applications: XML makes it easier to express metadata in a portable,
reusable format.
6. Pervasive computing: XML provides portable and structured information types for
display on pervasive (wireless) computing devices such as personal digital
assistants (PDAs), cellular phones, and others. For example, WML (Wireless
Markup Language) and VoiceXML are currently evolving standards for describing
visual and speech-driven wireless device interfaces.
7. The syntax rules of XML are very simple and logical. The rules are easy to learn, and
easy to use.

XML Documents Must Have a Root Element


XML documents must contain one root element that is the parent of all other elements:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

In this example <note> is the root element:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML Prolog


This line is called the XML prolog:

<?xml version="1.0" encoding="UTF-8"?>

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 the default character encoding for XML documents.

Character encoding can be studied in our Character Set Tutorial.

UTF-8 is also the default encoding for HTML5, CSS, JavaScript, PHP, and SQL.

All XML Elements Must Have a Closing Tag


In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<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.

XML Tags are Case Sensitive


XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.

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.

XML Elements Must be Properly Nested


In HTML, you might see improperly nested elements:

<b><i>This text is bold and italic</b></i>

In XML, all elements must be properly nested within each other:

<b><i>This text is bold and italic</i></b>

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.

XML Attribute Values Must Always be Quoted


XML elements can have attributes in name/value pairs just like in HTML.

In XML, the attribute values must always be quoted:

<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.

This will generate an XML error:

<message>salary < 1000</message>

To avoid this error, replace the "<" character with an entity reference:

<message>salary &lt; 1000</message>

There are 5 pre-defined entity references in XML:

&lt; < less than

&gt; > greater than

&amp; & ampersand

&apos; ' Apostrophe

&quot; " quotation mark

Only < and & are strictly illegal in XML, but it is a good habit to replace > with &gt; as well.

Comments in XML
The syntax for writing comments in XML is similar to that of HTML:

<!-- This is a comment -->


Two dashes in the middle of a comment are not allowed:

<!-- This is an invalid -- comment -->

White-space is Preserved in XML


XML does not truncate multiple white-spaces (HTML truncates multiple white-spaces to one
single white-space):

XML: Hello Tove

HTML: Hello Tove

XML Stores New Line as LF


Windows applications store a new line as: carriage return and line feed (CR+LF).

Unix and Mac OSX use LF.

Old Mac systems use CR.

XML stores a new line as LF.

Well Formed XML


XML documents that conform to the syntax rules above are said to be "Well Formed" XML
documents.

STRUTS

MODEL VIEW ARCHITECTURE


The Model-View-Controller (MVC) is a well-known design pattern in the web development field. It is
way to organize our code. It specifies that a program or application shall consist of data model,
presentation information and control information. The MVC pattern needs all these components to be
separated as different objects.
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and disadvantages
and examples to understand the implementation of MVC in Java.

What is MVC architecture in Java?


The model designs based on the MVC architecture follow MVC design pattern. The application logic is
separated from the user interface while designing the software using model designs.
The MVC pattern architecture consists of three layers:
660.2K

Amazon planning to cut around 10,000 employees

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.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:
o MVC has the feature of scalability that in turn helps the growth of application.

o The components are easy to maintain because there is less dependency.

o A model can be reused by multiple views that provides reusability of code.

o The developers can work with the three layers (Model, View, and Controller)
simultaneously.

o Using MVC, the application becomes more understandable.

o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.

o The extending and testing of application is easier.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following three classes.
o Employee Class, will act as model layer

o EmployeeView Class, will act as a view layer

o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers


Model Layer
The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetches and
stores the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.
Let's consider the following code snippet that creates a model which is also the first step to
implement MVC pattern.
Employee.java
1. // class that represents model
2. public class Employee {
3.
4. // declaring the variables
5. private String EmployeeName;
6. private String EmployeeId;
7. private String EmployeeDepartment;
8.
9. // defining getter and setter methods
10. public String getId() {
11. return EmployeeId;
12. }
13.
14. public void setId(String id) {
15. this.EmployeeId = id;
16. }
17.
18. public String getName() {
19. return EmployeeName;
20. }
21.
22. public void setName(String name) {
23. this.EmployeeName = name;
24. }
25.
26. public String getDepartment() {
27. return EmployeeDepartment;
28. }
29.
30. public void setDepartment(String Department) {
31. this.EmployeeDepartment = Department;
32. }
33.
34. }
The above code simply consists of getter and setter methods to the Employee class.

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. }

Main Class Java file


The following example displays the main file to implement the MVC architecture. Here, we are using the
MVCMain class.
MVCMain.java
1. // main class
2. public class MVCMain {
3. public static void main(String[] args) {
4.
5. // fetching the employee record based on the employee_id from the database
6. Employee model = retriveEmployeeFromDatabase();
7.
8. // creating a view to write Employee details on console
9. EmployeeView view = new EmployeeView();
10.
11. EmployeeController controller = new EmployeeController(model, view);
12.
13. controller.updateView();
14.
15. //updating the model data
16. controller.setEmployeeName("Nirnay");
17. System.out.println("\n Employee Details after updating: ");
18.
19. controller.updateView();
20. }
21.
22. private static Employee retriveEmployeeFromDatabase(){
23. Employee Employee = new Employee();
24. Employee.setName("Anu");
25. Employee.setId("11");
26. Employee.setDepartment("Salesforce");
27. return Employee;
28. }
29. }
The MVCMain class fetches the employee data from the method where we have entered the values. Then
it pushes those values in the model. After that, it initializes the view (EmployeeView.java). When view is
initialized, the Controller (EmployeeController.java) is invoked and bind it to Employee class and
EmployeeView class. At last the updateView() method (method of controller) update the employee details to
be printed to the console.
Output:
Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce

Employee Details after updating:


Name: Nirnay
Employee ID: 11
Employee Department: Salesforce
In this way, we have learned about MVC Architecture, significance of each layer and its implementation in
Java.

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:

● The web.xml file maps URLs to servlet classes.


● Servlet classes contain doGet() and doPost() functions to handle
requests.
● JSP files contain HTML and Java code to create a view.
This approach will work, and if you’re happy with this setup, that’s completely
okay! You don’t need to learn about Struts or other frameworks to get stuff
working. But if you’re annoyed by things like parsing multiple URLs to handle
them in the same servlet class or sharing data between servlets, or if you’re
planning on working on a bigger professional project, then you might want to
learn about frameworks like Struts.

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:

● A library is code that you use inside your code.


● A framework is code that you put your code inside.
If you’re using a library, you’re still using the overall setup and flow of whatever
language you’re programming in: you’re using a main() method, or a servlet class
with a doGet() function, for example. Compare that to a framework, which sits in
between the underlying flow of the language and your code. So instead of writing
your code inside a doGet() function, you’ll write your code inside whatever
function the framework provides. That’s probably a little confusing right now, but
hopefully it will make more sense by the end of this tutorial, which introduces a
framework called Struts.

A Struts web app looks like this:

● A stuts.xml file maps URLs to action classes.


● Action classes contain functions that map to particular URLs.
● JSP files contain HTML and Java code to create a view, and
Struts tags provide access to data in our action classes.
The idea is that Struts allows us to simplify our code, because we don’t have to
deal with the “low level” URL mapping and servlet classes.

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.)

Create a Web App Directory


By now you’re probably pretty familiar with this step. Either create a directory for
your web app (if you’re using the command line to compile and run stuff), or
create a project in Eclipse. Copy the .jar files from the folder you just unzipped
into the WEB-INF/libs folder of your web app directory, like we covered in the
libraries tutorial.

Create a web.xml File


Next, we need to write a web.xml file that tells our server to let the Struts
framework handle all of the requests:

<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.

Create an Action Class


Instead of servlets, Struts uses action classes that allow you to write code that
runs when the server receives a request from a user. Here’s an example action
class:

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{

private String messageToDisplay;

@Override
public String execute(){
messageToDisplay = "Happy coding!";
return ActionSupport.SUCCESS;
}

public String getMessage(){


return messageToDisplay;
}
}

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.)

Create a JSP View


Notice that our action class doesn’t render any HTML. This is because we should
use a JSP file to render HTML. Here’s an example JSP file:

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.

Create a struts.xml File


Finally, we need to map the requests that Struts receives to the action classes
and JSP views we want to use. We do that using a struts.xml file, which is a little
bit like the web.xml file except it tells Struts what to do.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

<package name="helloworld" namespace="/" extends="struts-default">


<action name="hello" class="HelloWorldAction">
<result name="success">WEB-INF/jsp/hello.jsp</result>
</action>
</package>
</struts>
This might seem confusing at first, but let’s take it piece by piece:

● The first couple of lines just define an XML declaration and


specify a Struts version, which the underlying XML parser uses
to understand the rest of the file.
● <struts> is the top-level element that will contain other elements.
● <package> defines a group of action classes. How you group them
is up to you.
● name allows you to name your group. This can be anything you
want.
● namespace specifies the first part of the URL to map. In this case
we’re using /, which means our URLs are relative to the top of
our domain.
● extends tells Struts to hook up its default behaviors to our code.
● <action> maps an action class to a URL.
● name specifies the rest of the URL, which it combines with
the namespace attribute to create a URL to map. In this case the
URL will be /hello.
● class specifies the action class whose execute() function should be
called when a user requests the mapped URL.
● <result> tells Struts which JSP view should be rendered
depending on what value is returned from the execute() function.
● name maps to a value returned from the execute() function. This
matches the value in our action class.
● The content of the <result> tag specifies a path to a JSP file that
should be used to render the view when the action class returns
a value that matches the name attribute.
Your struts.xml file can contain multiple <package> elements, which can contain
multiple <action> elements, which can contain multiple <result> elements. When
a request is made, Struts finds the action class that matches the URL, and calls
its execute() function. It then finds the result that matches the value returned from
that function, and renders the view using that JSP file.

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.

When we visit http://localhost:8080/hello, we should see this:

Struts 2 Architecture and Flow


The architecture and flow of struts 2 application, is combined with many
components such as Controller, ActionProxy, ActionMapper, Configuration
Manager, ActionInvocation, Inerceptor, Action, Result etc.
Here, we are going to understand the struts flow by 2 ways:
1. struts 2 basic flow
2. struts 2 standard architecture and flow provided by apache struts

Struts 2 basic flow


Let's try to understand the basic flow of struts 2 application by this simple
figure:
1. User sends a request for the action
2. Controller invokes the ActionInvocation
3. ActionInvocation invokes each interceptors and action
4. A result is generated
5. The result is sent back to the ActionInvocation
6. A HttpServletResponse is generated
7. Response is sent to the user

Struts 2 standard flow (Struts 2 architecture)


Let's try to understand the standard architecture of struts 2 application by
this simple figure:
Play Videox

1. User sends a request for the action


2. Container maps the request in the web.xml file and gets the class
name of controller.
3. Container invokes the controller (StrutsPrepareAndExecuteFilter or
FilterDispatcher). Since struts2.1, it is
StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher.
4. Controller gets the information for the action from the ActionMapper
5. Controller invokes the ActionProxy
6. ActionProxy gets the information of action and interceptor stack from
the configuration manager which gets the information from the
struts.xml file.
7. ActionProxy forwards the request to the ActionInvocation
8. ActionInvocation invokes each interceptors and action
9. A result is generated
10. The result is sent back to the ActionInvocation
11. A HttpServletResponse is generated
12. Response is sent to the user

Struts features

The important features of struts 2 framework are as follows:

1. Configurable MVC components


2. POJO based actions
3. AJAX support
4. Integration support
5. Various Result Types
6. Various Tag support
7. Theme and Template support

1) Configurable MVC components In struts 2 framework, we provide


all the components (view components and action) information in
struts.xml file. If we need to change any information, we can simply
change it in the xml file.

2) POJO based actions In struts 2, action class is POJO (Plain Old


Java Object) i.e. a simple java class. Here, you are not forced to
implement any interface or inherit any class.

3) AJAX support Struts 2 provides support to AJAX technology. It is


used to make asynchronous request i.e. it doesn't block the user. It
sends only required field data to the server side not all. So it makes
the performance fast

4) Integration Support We can simply integrate the struts 2


application with hibernate, spring, tiles etc. frameworks.

5) Various Result Types We can use JSP, freemarker, velocity etc.


technologies as the result in struts 2.
6) Various Tag support Struts 2 provides various types of tags such
as UI tags, Data tags, control tags etc to ease the development of
struts 2 application.

7) Theme and Template support Struts 2 provides three types of


theme support: xhtml, simple and css_xhtml. The xhtml is default
theme of struts 2. Themes and templates can be used for common
look and feel.

Coding a Struts 2 Action involves several parts:

1. Mapping an action to a class


2. Mapping a result to a view
3. Writing the controller logic in the Action class

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

<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction"


method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>

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


Action classes act as the controller in the MVC pattern. Action classes respond to a user action, execute
business logic (or call upon other classes to do that), and then return a result that tells Struts what view to
render.

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.

Method execute of HelloWorldAction

public String execute() throws Exception {


messageStore = new MessageStore() ;

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.

Processing Form Input In The Action Class


One of the most common responsibilities of the Action class is to process user input on a form and then
make the result of the processing available to the view page. To illustrate this responsibility, let’s say that
on our view page, HelloWorld.jsp, we want to display a personal hello, such as “Hello Struts User
Bruce.”

In the Using Struts 2 Tags example application we added a Struts 2 form to index.jsp.

Struts 2 Form Tags

<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

private String userName;

public String getUserName() {


return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

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.

Add userName value to message

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.

Forms and a Java model class


For this tutorial let’s say we need to provide a form that a user may submit to register for a prize drawing.
Our business rules state the user must provide his/her first name, last name, email address, and age.

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

public class Person {


private String firstName;
private String lastName;
private String email;
private int age;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public String toString() {


return "First Name: " + getFirstName() + " Last Name: " + getLastName() +
" Email: " + getEmail() + " Age: " + getAge() ;
}
}
Note a few points about the above class. There is a public set/get method for each instance field. The age
attribute is of type integer. We’ve defined a public toString method that returns a String representing the
state of the object. Since we haven’t specified a constructor, Java will provide a default constructor that
will set all instance fields to their null values.

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

<%@ taglib prefix="s" uri="/struts-tags" %>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Register</title>
</head>
<body>
<h3>Register for a prize by completing this form.</h3>

<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.

Creating the Action class to handle the form submission


When the user clicks on the submit button of the above form, the action “register” and the form data will
be sent to the Struts 2 framework. We need an Action class to process this form. If you recall from the
tutorial Coding Struts 2 Actions our Action class should extend the Struts 2 ActionSupport class.

Here is the Action class used for this example. Place it in package org.apache.struts.register.action.

Register.java Struts 2 Action Class

package org.apache.struts.register.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts.register.model.Person;

public class Register extends ActionSupport {

private static final long serialVersionUID = 1L;

private Person personBean;

public String execute() throws Exception {


//call Service class to store personBean's state in database

return SUCCESS;
}

public Person getPersonBean() {


return personBean;
}

public void setPersonBean(Person person) {


personBean = person;
}

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.

Adding the view for the result


When SUCCESS is returned by the execute method we want to display a simple thank you page that shows
the user’s registration. Add the thankyou.jsp below to src/main/webapp.

thankyou.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Registration Successful</title>
</head>
<body>
<h3>Thank you for registering for a prize.</h3>

<p>Your registration information: <s:property value="personBean" /> </p>

<p><a href="<s:url action='index' />" >Return to home page</a>.</p>


</body>
</html>

If you don’t recall how the Struts 2 property and url tags work consult the Using Struts 2 Tags tutorial.

Create action mapping in struts.xml


To specify the relationship between the form submission page, the Struts 2 Action class, and the success
view page we need to add an action node to struts.xml. Add this action node
to struts.xml (src/main/resources) after the hello action and before the closing package node.

action node for struts.xml

<action name="register" class="org.apache.struts.register.action.Register"


method="execute">
<result name="success">/thankyou.jsp</result>
</action>

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).

Create a link to register.jsp


So that the user can find the registration page, add this link to index.jsp

Link to register.jsp

<p><a href="register.jsp">Please register</a> for our prize drawing.</p>

Run The Example


If everything is correct, you should be able to run the application (using mvn jetty:run), and open this
URL in your web browser: http://localhost:8080/form-processing/index.action. On that page should be a
link to register. Click on that link and you should see the register.jsp page.

Fill out the form and click the submit button. You should then see the thankyou.jsp page.

Add validate Method


To enable the Struts 2 Action class to validate a user’s input on a Struts 2 form, you must define a
validate method in your Action class. Using the example from Processing Forms tutorial, let’s say that we
have these business rules:

1. User must provide a first name


2. User must provide an email address
3. User younger than 18 cannot register

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.

Add the following validate method to Register.java (the Action class).

validate method

public void validate(){


if (personBean.getFirstName().length() == 0) {
addFieldError("personBean.firstName", "First name is required.");
}

if (personBean.getEmail().length() == 0) {
addFieldError("personBean.email", "Email is required.");
}

if (personBean.getAge() < 18) {


addFieldError("personBean.age", "Age is required and must be 18 or older");
}
}

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.

Handle Input Being Returned


So what should we do if Struts 2 returns input indicating that the user’s input in the form is not valid? In
most cases we will want to redisplay the web page that has the form and include in the form error
messages to inform the user what is wrong.

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.

So the following addFieldError method call:

addFieldError("personBean.firstName", "First name is required.")

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.

Styling The Error Messages


The Struts 2 s:head tag can be used to provide CSS that includes a style for the error message.
Add <s:head /> to register.jsp before the closing HTML </head> tag.
There is another more sophisticated way to validate user input using XML. If you want to learn more
about using XML for validation in Struts 2 see Validation .

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>

Beginning with version 2.0.4 Struts provides an extension to


XWork’s com.opensymphony.xwork2.validator.ValidationInterceptor interceptor.

<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.

Defining Validation Rules


Validation rules can be specified:

1. Per Action class: in a file named ActionName-validation.xml


2. Per Action alias: in a file named ActionName-alias-validation.xml
3. Inheritance hierarchy and interfaces implemented by Action class: XWork searches up the
inheritance tree of the action to find default validations for parent classes of the Action and
interfaces implemented

Here is an example for SimpleAction-validation.xml:

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"


"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="bar">
<field-validator type="required">
<message>You must enter a value for bar.</message>
</field-validator>
<field-validator type="int">
<param name="min">6</param>
<param name="max">10</param>
<message>bar must be between ${min} and ${max}, current value is
${bar}.</message>
</field-validator>
</field>
<field name="bar2">
<field-validator type="regex">
<param name="expression">[0-9],[0-9]</param>
<message>The value of bar2 must be in the format "x, y", where x and y are
between 0 and 9</message>
</field-validator>
</field>
<field name="date">
<field-validator type="date">
<param name="min">12/22/2002</param>
<param name="max">12/25/2002</param>
<message>The date must be between 12-22-2002 and 12-25-2002.</message>
</field-validator>
</field>
<field name="foo">
<field-validator type="int">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
<validator type="expression">
<param name="expression">foo lt bar </param>
<message>Foo must be greater than Bar. Foo = ${foo}, Bar = ${bar}.</message>
</validator>
</validators>

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.

Customizing validation messages

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.

The final output will be as follow:

Username is required.

Annotations

The same mechanism can be used with annotations as follow:

@RequiredStringValidator(key = "errors.required", messageParams = {


"getText('username.field.name')"
})
public void setUsername(String username) {
this.username = username;
}

Validator Flavor
The validators supplied by the XWork distribution (and any validators you might write yourself) come in
two different flavors:

1. Plain Validators / Non-Field validators


2. FieldValidators

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.

Non-Field Validator Vs Field-Validator validatortypes


There are two ways you can define validators in your -validation.xml file:

1. <validator>
2. <field-validator>

Keep the following in mind when using either syntax:

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)

Declaring a FieldValidator using the <field-validator> syntax:

<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.

<!DOCTYPE validators PUBLIC


"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<!-- Field Validators for email field -->
<field name="email">
<field-validator type="required" short-circuit="true">
<message>You must enter a value for email.</message>
</field-validator>
<field-validator type="email" short-circuit="true">
<message>Not a valid e-mail.</message>
</field-validator>
</field>
<!-- Field Validators for email2 field -->
<field name="email2">
<field-validator type="required">
<message>You must enter a value for email2.</message>
</field-validator>
<field-validator type="email">
<message>Not a valid e-mail2.</message>
</field-validator>
</field>
<!-- Plain Validator 1 -->
<validator type="expression">
<param name="expression">email.equals(email2)</param>
<message>Email not the same as email2</message>
</validator>
<!-- Plain Validator 2 -->
<validator type="expression" short-circuit="true">
<param name="expression">email.startsWith('mark')</param>
<message>Email does not start with mark</message>
</validator>
</validators>

short-circuiting and Validator flavors

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.

In the example above, the actual execution of validator would be as follows:

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.

Short cuircuiting and validator flavours

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="required" short-circuit="true">


<param name="fieldName">bar</param>
<message>You must enter a value for bar.</message>
</validator>

<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.

How Validators of an Action are Found


As mentioned above, the framework will also search up the inheritance tree of the action to find default
validations for interfaces and parent classes of the Action. If you are using the short-circuit attribute and
relying on default validators higher up in the inheritance tree, make sure you don’t accidentally short-
circuit things higher in the tree that you really want!

The effect of having common validators on both

● <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.

Writing custom validators


If you want to write custom validator use on of these classes as a starting point:

● 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.

There are following advantages of tiles framework:


o Customization by centralized page We can customize the layout of all the pages by single page
(centralized page) only.
o Code reusability A single part e.g. header or footer can be used in many pages. So it saves coding.
o Easy to modify If any part (tile) is modified, we don't need to change many pages.
o Easy to remove If any part (tile) of the page is removed, we don't need to remove the code from all
the pages. We can remove the tile from our layout manager page.

Steps to create tiles application


The steps are as follows:
1. Add tiles library in your application
2. Define Struts2TilesListener in web.xml file
3. Create the input page (index.jsp)
4. Create the Action class
5. Extend the tiles-default package in your package and define all the result type as tiles in struts.xml
file
6. Create the tiles.xml file and define all the tiles definitions
7. Create the LayoutManager page
8. Create the View components

1) Add tiles library in your application


If you are using myeclipse IDE, you can add tiles library by right click on the project -> Build Path -> Add
Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok.
If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your project.
download the struts2 jar files

2) Define Struts2TilesListener in web.xml file


Provide entry of listener class Struts2TilesListener in the web.xml file.
web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5"
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
7. <welcome-file-list>
8. <welcome-file>index.jsp</welcome-file>
9. </welcome-file-list>
10. <filter>
11. <filter-name>struts2</filter-name>
12. <filter-class>
13. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
14. </filter-class>
15. </filter>
16. <filter-mapping>
17. <filter-name>struts2</filter-name>
18. <url-pattern>/*</url-pattern>
19. </filter-mapping>
20.
21. <listener>
22. <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
23. </listener>
24.
25. </web-app>
3) Create the input page (index.jsp)
index.jsp
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2.
3. <s:form action="login">
4. <s:textfield name="name" label="Name"></s:textfield>
5. <s:password name="password" label="Password"></s:password>
6. <s:submit value="login"></s:submit>
7. </s:form>

4) Create the action class


This action class contains one field name and defines the execute method.
Login.java
1. package com.javatpoint;
2.
3. public class Login {
4. private String name,password;
5.
6. //getters and setters
7.
8. public String execute(){
9. if(password.equals("admin")){
10. return "success";
11. }
12. else{
13. return "error";
14. }
15. }
16. }

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>

7) Create the LayoutManager page


It is the layout manager page. It used getAsString tag of tiles to include the string resource and insertAttribute
tag of tiles to include the page resource.
layoutmanager.jsp
1. <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3. "http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <title><tiles:getAsString name="title" /></title>
7. </head>
8. <body>
9.
10. <%@ include file="header.jsp" %>
11. <tiles:insertAttribute name="body" />
12. <%@ include file="footer.jsp" %>
13.
14. </body>
15. </html>

8)Create View components


There are many view components such as header.jsp, footer.jsp, welcome.jsp etc.
header.jsp
1. <h2 style="background-color:pink;text-align:center;">It is header tile</h2>
2. <hr/>

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:

Password is not admin, so error page will be displayed.


If password is admin, success page will be displayed.

How to define multiple tiles files in struts 2 applicaiton


To define multiple tiles, you need to add following entry in your web.xml file.
1. <context-param id="struts_tiles">
2. <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
3. <param-value>/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value>
4. </context-param>

You might also like