0% found this document useful (0 votes)
27 views

Struts Architecture Control Flow and Validation Framework

The document provides an introduction to the Struts 2 framework, describing its features and architecture. Struts 2 is an MVC framework for developing Java web applications. It allows for configurable components, POJO-based actions, integration with other frameworks, and supports AJAX, themes, and multiple view technologies.

Uploaded by

Dhruv Kakkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Struts Architecture Control Flow and Validation Framework

The document provides an introduction to the Struts 2 framework, describing its features and architecture. Struts 2 is an MVC framework for developing Java web applications. It allows for configurable components, POJO-based actions, integration with other frameworks, and supports AJAX, themes, and multiple view technologies.

Uploaded by

Dhruv Kakkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Introduction to Struts 2

The struts 2 framework is used to develop MVC-based web


application.

The struts framework was initially created by Craig McClanahan


and donated to Apache Foundation in May, 2000 and Struts 1.0 was
released in June 2001.

The current stable release of Struts is Struts 2.3.16.1 in March 2,


2014.

The Struts 2 framework is used to develop MVC (Model View Controller)


based web applications. Struts 2 is the combination of webwork
framework of opensymphony and struts 1.

The Struts 2 provides supports to POJO based actions, Validation Support, AJAX
Support, Integration support to various frameworks such as Hibernate, Spring,
Tiles etc, support to various result types such as Freemarker, Velocity, JSP etc.

Struts 2 Features
Struts 2 provides many features that were not in struts 1. 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.
Model 1 and Model 2 (MVC) Architecture
Before developing the web applications, we need to have idea about design
models. There are two types of programming models (design models)

1. Model 1 Architecture
2. Model 2 (MVC) Architecture

Model 1 Architecture
Servlet and JSP are the main technologies to develop the web applications.

Servlet was considered superior to CGI. Servlet technology doesn't create


process, rather it creates thread to handle request. The advantage of creating
thread over process is that it doesn't allocate separate memory area. Thus many
subsequent requests can be easily handled by servlet.

Problem in Servlet technology Servlet needs to recompile if any designing code


is modified. It doesn't provide separation of concern. Presentation and Business
logic are mixed up.

JSP overcomes almost all the problems of Servlet. It provides better separation
of concern, now presentation and business logic can be easily separated. You
don't need to redeploy the application if JSP page is modified. JSP provides
support to develop web application using JavaBean, custom tags and JSTL so
that we can put the business logic separate from our JSP that will be easier to
test and debug.
As you can see in the above figure, there is picture which show the flow of the model1
architecture.

1. Browser sends request for the JSP page


2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture


Easy and Quick to develop web application
Disadvantage of Model 1 Architecture
Navigation control is decentralized since every page contains the logic to determine the
next page. If JSP page name is changed that is referred by other pages, we need to change
it in all the pages that leads to the maintenance problem.
Time consuming You need to spend more time to develop custom tags in JSP. So that
we don't need to use scriptlet tag.
Hard to extend It is better for small applications but not for large applications.

Model 2 (MVC) Architecture


Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern
consists of three modules model, view and controller.

Model The model represents the state (data) and business logic of the application.

View The view module is responsible to display data i.e. it represents the presentation.

Controller The controller module acts as an interface between view and model. It intercepts all
the requests i.e. receives input and commands to Model / View to change accordingly.

Advantage of Model 2 (MVC) Architecture


• Navigation control is centralized Now only controller contains the logic to determine the next
page.
• Easy to maintain
• Easy to extend
• Easy to test
• Better separation of concerns
Disadvantage of Model 2 (MVC) Architecture
• We need to write the controller code self. If we change the controller code, we need to
recompile the class and redeploy the application
Struts 2 Architecture and Control 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 Control Flow (Struts 2 Architecture)


Let's try to understand the standard architecture of struts 2
application by this simple figure:
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).
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

Steps to create Struts 2 Application Example


In this example, we are creating the struts 2 example without IDE. We can simply create the
struts 2 application by following these simple steps:

1. Create the directory structure


2. Create input page (index.jsp)
3. Provide the entry of Controller in (web.xml) file
4. Create the action class (Product.java)
5. Map the request with the action in (struts.xml) file and define the view components
6. Create view components (welcome.jsp)
7. load the jar files
8. start server and deploy the project

1) Create the directory structure

The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located in
the classes folder.
2) Create input page (index.jsp)

This jsp page creates a form using struts UI tags. To use the struts UI tags, you
need to specify uri /struts-tags. Here, we have used s:form to create a form,
s:textfield to create a text field, s:submit to create a submit button.

index.jsp

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


2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>

3) Provide the entry of Controller in (web.xml) file

In struts 2, StrutsPrepareAndExecuteFilter class works as the controller. As we


know well, struts 2 uses filter for the controller. It is implicitly provided by the
struts framework.

web.xml

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


2. <web-app>
3. <filter>
4. <filter-name>struts2</filter-name>
5. <filter-class>
6. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
7. </filter-class>
8. </filter>
9. <filter-mapping>
10. <filter-name>struts2</filter-name>
11. <url-pattern>/*</url-pattern>
12. </filter-mapping>
13.</web-app>

4) Create the action class (Product.java)

This is simple bean class. In struts 2, action is POJO (Plain Old Java Object).
It has one extra method execute i.e. invoked by struts framework by default.
Product.java

package com.swar;

public class Product {

private int id;

private String name;

private float price;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getPrice() {

return price;

public void setPrice(float price) {


this.price = price;

public String execute(){

return "success";

5) Map the request in (struts.xml) file and define the view components

It is the important file from where struts framework gets information about the
action and decides which result to be invoked. Here, we have used many
elements such as struts, package, action and result.

Struts element is the root elements of this file. It represents an application.

Package element is the sub element of struts. It represents a module of the


application. It generally extends the struts-default package where many
interceptors and result types are defined.

Action element is the sub element of package. It represents an action to be


invoked for the incoming request. It has name, class and method attributes. If
you don't specify name attribute by default execute() method will be invoked
for the specified action class.

Result element is the sub element of action. It represents an view (result) that
will be invoked. Struts framework checks the string returned by the action
class, if it returns success, result page for the action is invoked whose name is
success or has no name. It has name and type attributes. Both are optional. If
you don't specify the result name, by default success is assumed as the result
name. If you don't specify the type attribute, by default dispatcher is considered
as the default result type.

struts.xml

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


2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.abc.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11.</package>
12. </struts>

6) Create view components (welcome.jsp)

It is the view component the displays information of the action. Here, we are
using struts tags to get the information.

The s:property tag returns the value for the given name, stored in the action
object.

welcome.jsp

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


2.
3. Product Id:<s:property value="id"/><br/>
4. Product Name:<s:property value="name"/><br/>
5. Product Price:<s:property value="price"/><br/>

7) Load the jar files

To run this application, you need to have the struts 2 jar files. Here, we are
providing all the necessary jar files for struts 2. Download it and put these jar
files in the lib folder of your project.

Now copy following files from struts 2 lib folder C:\struts-2.2.3\lib to our project's WEB-INF\lib
folder. To do this, you can simply drag and drop all the following files into WEB-INF\lib folder.
commons-fileupload-x.y.z.jar
commons-io-x.y.z.jar
commons-lang-x.y.jar
commons-logging-x.y.z.jar
commons-logging-api-x.y.jar
freemarker-x.y.z.jar
javassist-.xy.z.GA
ognl-x.y.z.jar
struts2-core-x.y.z.jar
xwork-core.x.y.z.jar
8) start server and deploy the project

Finally, start the server and deploy the project and access it.

Example to create struts 2 application in MyEclipse


Here, we are going to create the struts 2 application using myeclipse ide. We don't need to care
about the jar files because MyEclipse provides these jar files.

You need to follow these steps to create struts 2 application.

1. Create a web project


2. Add struts 2 capabilities
3. Create input page (index.jsp)
4. Create the action class (Product.java)
5. Map the request with the action in (struts.xml) file and define the view components
6. Create view components (welcome.jsp)
7. start server and deploy the project

1) Create a web project

To create web project, click on the file menu - new - project - web project - write the project
name e.g. firststruts - finish.
2) Add struts 2 capabilities

To add struts 2 capabilities, select you project - click on the myeclipse menu - add project
capabilities - add struts capabilities.

Select the 2.1 and /* as the url pattern - finish.

3) Create input page (index.jsp)

It uses struts core tags to create a form with fields.

index.jsp

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


2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>

4) Create the action class (Product.java)

It is the simple action class containing properties with setters and getters. It contains the execute
method also for defining the business logic.

Product.java
1. package com.javatpoint;
2.
3. public class Product {
4. private int id;
5. private String name;
6. private float price;
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name = name;
18. }
19. public float getPrice() {
20. return price;
21. }
22. public void setPrice(float price) {
23. this.price = price;
24. }
25.
26. public String execute(){
27. return "success";
28. }
29. }

5) Map the request in (struts.xml) file and define the view components

This xml file registers the action and view components.

struts.xml

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


2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>
6) Create view components (welcome.jsp)

This jsp page displays the information set in the action object.

welcome.jsp

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


2.
3. Product Id:<s:property value="id"/><br/>
4. Product Name:<s:property value="name"/><br/>
5. Product Price:<s:property value="price"/><br/>

7) start server and deploy the project

To start the server and deploy the project, right click on your project - Run As - MyEclipse
server application.

Struts Validation Framework


At the Struts core, we have the validation framework that assists the application to
run the rules to perform validation before the action method is executed.
Client side validation is usually achieved using Javascript. However, one should not
rely upon client side validation alone. The best practices suggest that the validation
should be introduced at all levels of your application framework. Now let us look at
two ways of adding validation to our Struts project.

Here, we will take an example of an Employee whose name and age should be
captured using a simple page, and we will put these two validations to make sure
that the user always enters a name and age which should be in a range between 28
and 65.

Let us start with the main JSP page of the example.

Create Main Page

Let us write main page JSP file index.jsp, which will be used to collect Employee related
information mentioned above.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"


pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Employee Form</title>
</head>

<body>
<s:form action = "empinfo" method = "post">
<s:textfield name = "name" label = "Name" size = "20" />
<s:textfield name = "age" label = "Age" size = "20" />
<s:submit name = "submit" label = "Submit" align="center" />
</s:form>
</body>
</html>

The index.jsp makes use of Struts tag. just assume that the s:textfield tag prints a input field, and
the s:submit prints a submit button. We have used label property for each tag which creates label
for each tag.

Create Views
We will use JSP file success.jsp which will be invoked in case defined action returns SUCCESS.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"


pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Success</title>
</head>

<body>
Employee Information is captured successfully.
</body>
</html>

Create Action
So let us define a small action class Employee, and then add a method called validate() as shown
below in Employee.java file. Make sure that your action class extends the ActionSupport class,
otherwise your validate method will not be executed.

package com.abc.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport {


private String name;
private int age;

public String execute() {


return SUCCESS;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public void validate() {


if (name == null || name.trim().equals("")) {
addFieldError("name","The name is required");
}

if (age < 28 || age > 65) {


addFieldError("age","Age must be in between 28 and 65");
}
}
}

As shown in the above example, the validation method checks whether the 'Name' field has a value
or not. If no value has been supplied, we add a field error for the 'Name' field with a custom error
message. Secondly, we check if entered value for 'Age' field is in between 28 and 65 or not, if this
condition does not meet we add an error above the validated field.

Configuration Files

Finally, let us put everything together using the struts.xml configuration file as follows −

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


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

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

<action name = "empinfo"


class = "com.abc.struts2.Employee"
method = "execute">
<result name = "input">/index.jsp</result>
<result name = "success">/success.jsp</result>
</action>

</package>
</struts>

Following is the content of web.xml file −


<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Now do not enter any required information, just click on Submit button. You will see the
following result:
Enter the required information but enter a wrong From field, let us say name as "test" and age as
30, and finally click on Submit button. You will see the following result.
How this Validation Works?
When the user presses the submit button, Struts 2 will automatically execute the validate method
and if any of the “if” statements listed inside the method are true, Struts 2 will call its addFieldError
method. 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.

Hence, when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the
index.jsp file. Since, we used Struts 2 form tags, Struts 2 will automatically add the error messages
just above the form filed.

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.

addFieldError("name","The name is required");

To handle the return value of input we need to add the following result to our action node in
struts.xml.

<result name="input">/index.jsp</result>

You might also like