SlideShare a Scribd company logo
STRUTS2.x
Struts 1
• MVC is a design pattern that facilitates
development of scalable, flexible
applications by segregating the
application components into one of the
following:
Model
View
Controller
 The model refers to those components of the application that do
the major work done by the application.
 In web application, models perform validation, implementation
of web logic, write and read to and from the database.
 The Model components majorly serve the following purpose:
 Represent the business entities. Instances of the model are used
to carry data around.
 Encapsulate functionalities provided by the application-
Database reading and writing validation etc.
 Decide the flow of execution of the application. Usually the
methods of the models decide the line of execution.
Models are the engine of the application. They contain most of
the code for what the application does. They are the busiest
code in an application
 View refers to the application’s face. It refers to that
component or group of components with which the user
interacts.
 When a user accesses/interacts with a web application,
he/she does it through web pages that are part of the web
application. These pages constitute the view.
 Views are generally used for the following purpose:
 Representing data entry forms.
 Representing reports-Tabular display of data.
Views are like the control panel. They are interfaces
through which data is entered. They also show results.
Views are what the data users see and experience in a web
application.
 The controller’s primary task is to act like a router.
 It moves data around the application in the form of
objects of the model.
 It is also responsible for initiating the execution of
model’s methods.
 After initiating the execution, the controller figures
out the result of the execution and accordingly
renders an appropriate view to the user.
Controller is the wiring of the web application. Responsible
mainly for data routing and also making the application run
along a certain path of execution.
Struts 1
 MVC pattern helps us achieve loose coupling by dividing
the application into the model, view and controller
components.
 Since the model and controller are independent of the
view, one view technology can easily swapped for the
other, application is not very affected in case of such a
view.
Struts 1
 Implementation of the MVC pattern done by Apache
Software Foundation.
 Web application development framework.
 Based on java technologies like Servlets, JSP, Java Beans
 Present in two major flavors:
• Version 1.x
• Version 2.x
Provides rich libraries that automate several tasks involved
in developing web applications like AJAX, validation etc.
 Developed by Craig McClanaghan
 Donated to the Apache Software Foundation in the year 2000
 Ever since had been used in numerous projects across the world
and has been accepted as the web development framework of
choice.
 Early 2005, WebWork project spun off from struts framework.
 WebWork and Struts merge together in Feb 2007 and remerged
as struts 2.
 Current Version 2.3.1
 Struts is a java based MVC implementation.
 Java technologies have been used in realizing the
model, the view and the controller.
 These components are implemented through the
following:
 Model-Action Classes(Simple classes also known as
POJO’s)
 View-JSP Pages
 Controller-Servlet Filter
 Models in Struts are normal Java classes.
 These classes usually have properties to hold data. For instance
the data posted by a form is held in an Action class via the
member variables.
 These classes also have methods that contain the business logic
of the application like validation, saving data to database or
retrieve data from the perspective of the application etc.
 These methods may themselves do the task or call methods
present in other classes, just to introduce modularity.
 The methods return a string that represents the result of the
activity performed by the method.
 Action classes are simply java classes. So they need not extend or
implement any class or interface as such.
 There are classes and interfaces however in the Struts library that make
the task of creating action classes a little simpler.
 Often action classes may also inherit from either:
 The Action interface
 The ActionSupport class(which in turn implements the Action interface)
 Inheriting from the Action interface or ActionSupport class provides
utility functions for doing stock activities like validation etc.
 let us proceed for building our first Hello
World struts2 project.
 The aim of this project is to build a web
application that collects the user's name and
displays "Hello World" followed by the user
name.
public class HelloWorldAction{
private String name;
public String execute() throws Exception { return "success"; }
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
 Views are one of the most beautiful aspect of Struts
framework.
 Views are JSP pages.
 Views may be forms or reports.
 Struts provides a rich set of tags(struts-tags) that
make creating forms and incorporating validation into
them easier than plain JSP.
 So, lets go ahead and create a file-HelloWorld.jsp in
our project
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head> <body> Hello World, <s:property value="name"/>
</body>
</html>
We also need to create one page “index.jsp”. This file will serve as the initial action URL
where a user can click to tell the Struts 2 framework to call the a defined method of the
HelloWorldAction class and render the HelloWorld.jsp view.
<%@ 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>Hello World</title>
</head>
<body> <h1>Hello World From Struts2</h1>
<form action="hello"> <label for="name">Please enter your name</label><br/>
<input type="text" name="name"/>
<input type="submit" value="Say Hello"/>
</form>
</body>
</html>
 Finally comes the controller
 Well very less often do we build controllers. The struts libraries provide
us with a controller that does almost all that needs to be done.
 The controller is a Servlet filter by the name: FilterDispatcher.
 All that we need to do is configure the web app in such a manner that,
all requests are routed through the FilterDispatcher.
 The FilterDispatcher is configured using an xml configuration file that
goes by the name struts.xml. Its contained in WEB-INF.
 Primarily it contains the various possible outcomes of actions and the
target the outcomes map to.
 In order to configure the controller add the following code to the web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<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>
This would make sure all requests that are received by the web server are route through the
filter(Controller).
 We are almost done but there is one last thing that needs to be done i.e.
wiring the action class up to the rest of the application.
 Forms can easily submit data to JSP pages or servlets. In case we want
the data to be submitted to an Action class, we need to route it through
the FilterDispatcher.
 The FilterDispatcher looks up the struts configuration file and decided
which Action class has to be instantiated and whose method has to be
called.
 Configuration information related to Action classes are stored in the
struts.xml file.
 This file should be present in the same place where other classes are
stored, i.e. /WEB-INF/classes.
 Type the following code into the struts.xml
file.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software
Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-
2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="hello“ class="com.tutorialspoint.struts2.HelloWorldAction"
method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
 Code mentioned in previous slide defines an action
called HelloWorldAction.
 For this action’s execute method, if the string
“success” is returned then HelloWorld.jsp is
dispatched to the client.
 There can be more than one results of the action
all defined within the action tag.
 Finally the application can be deployed and executed.
 Some error scenarios:
 Tomcat startup errors may be due to:
 Wrong data in struts.xml or web.xml
 Incompatible jar files in the lib folder
 Resource not found errors may be again due to the
same reasons. So please check web.xml and
struts.xml files.
Struts 1
 One of the good things in Struts 2.x is that Action classes need
not be special. They can be normal classes(classes that do not
inherit any other class or interface)
 You may however at times create Action classes by:
 Inheriting the Action interface
 Extending the ActionSupport class.
 The action class also may have methods other than the execute
method that can be invoked by the FilterDispatcher, provided its
name is present in the struts.xml file.
 Action classes that implement the Action interface inherit five
variables:
 public static final String SUCCESS=“success”
 public static final String NONE=“none”
 public static final String ERROR=“error”
 public static final String INPUT=“input”
 public static final String LOGIN=“login”
 These variables are symbolic of what next should happen after
the action class method is executed. They can be returned from
the methods and appropriate mapping provided in the struts.xml
file.
 The following table lists the constants and their meanings:
Result Meaning/Description
SUCCESS The action was successful.
NONE The action was successful but do not
show a view.
ERROR The execution failed.
INPUT The action requires more input before
it can be executed.
LOGIN The action could not be completed as
the user is not logged in.
 The Action interface also contains the definition of the execute method:
Public String execute() throws Exception
 So in case you are implementing this interface to create the action class,
you need to override this method.
 It’s a good practice to implement this interface because that way we can
be sure that our class contains an execute() method.
 There is a disadvantage however. To compile such a class, the classpath
needs to be set to point to the jar file that contains the Action interface.
 The ActionSupport class implements the Action
interface and provides blank implementation for the
execute() method.
 Apart from Action, the ActionSupport class also
implements the following interface:
 Validateable
 ValidationAware
 TextProvider
 LocaleProvider
 Serializable
 This interface contains the validate() method. The definition
is:
 Public void validate()
 A blank implementation is provided in the ActionSupport
class.
 In our Action classes, this is where validation of the values
should be done.
 This interface contains an assortment of methods that a class should have if its
capable of storing validation messages. Few of the methods are:
 addActionError(String message)-This function is called to log an error message for
the action.
 addActionMessage(String message)-Log a message for this action.
 Collection<String> getActionErrors()-Retrieves the error messages for this action.
Can be used in views to retrieve the error messages that were logged related to
the action.
 Collection<String> getActionMessages()-Retrieves the messages for this action.
 addFieldError(String FieldName, String message)- This
method adds an error message for a particular field. Useful
when we want to show message in the form for fields.
 Map<String, List<String>> getFieldErrors – This method
returns the error messages logged for the various fields.
Again used in views to retrieve the error messages for
individual fields.
 These interfaces provide support for globalization and
localization.
 The TextProvider interface has method for loading resource
bundles. The actual implementation has to be provided by the
inheriting class.
 The LocaleProvider interface has methods to retrieve current
locale. Again the actual implementation has to be provided by
the inheriting class.
 The Serializable interface allows for persisting the
action class instances to streams.
 Particularly useful if the objects data has to be
persisted to files rather than to the database
management system.
 import com.opensymphony.xwork2.ActionSupport;
public class Login extends ActionSupport{
String username ,password;
// Getters and Setters
public void validate()
{
if(username==null||username.length()==0)
addFieldError(“username”, ”Username cannot be left empty,
please enter valid username”);
if(password==null||password.length()==0)
addFieldError(“password”, ”Password cannot be left empty ,
please enter valid username”);
}
public String execute()
{
return “success”;
}
}
 Understanding the advantages of MVC pattern for designing
application.
 Clearly understand the advantages of using the Struts 2.x for
building web applications
 Understand the usage of Model, View and Controller
components of Struts 2.x framework.
 Build web applications that use the features of Struts 2.x
framework
Struts 1

More Related Content

What's hot (20)

PPT
Struts 2 Overview
skill-guru
 
PPTX
Struts introduction
Muthukumaran Subramanian
 
PDF
Step by Step Guide for building a simple Struts Application
elliando dias
 
PPT
Struts course material
Vibrant Technologies & Computers
 
PPT
Struts(mrsurwar) ppt
mrsurwar
 
PPT
Introducing Struts 2
wiradikusuma
 
PDF
Struts presentation
Nicolaescu Petru
 
PPT
Struts,Jsp,Servlet
dasguptahirak
 
PDF
Struts2
Rajiv Gupta
 
PPTX
Apache Struts 2 Framework
Emprovise
 
PPTX
Struts & spring framework issues
Prashant Seth
 
PPT
Struts Introduction Course
guest764934
 
PPT
Struts2
Scott Stanlick
 
PDF
important struts interview questions
surendray
 
PPT
Struts2 course chapter 1: Evolution of Web Applications
JavaEE Trainers
 
PPTX
Introduction to ejb and struts framework
s4al_com
 
PPT
Struts2
shankar_b7
 
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
PDF
Struts notes
dssreenath
 
Struts 2 Overview
skill-guru
 
Struts introduction
Muthukumaran Subramanian
 
Step by Step Guide for building a simple Struts Application
elliando dias
 
Struts course material
Vibrant Technologies & Computers
 
Struts(mrsurwar) ppt
mrsurwar
 
Introducing Struts 2
wiradikusuma
 
Struts presentation
Nicolaescu Petru
 
Struts,Jsp,Servlet
dasguptahirak
 
Struts2
Rajiv Gupta
 
Apache Struts 2 Framework
Emprovise
 
Struts & spring framework issues
Prashant Seth
 
Struts Introduction Course
guest764934
 
important struts interview questions
surendray
 
Struts2 course chapter 1: Evolution of Web Applications
JavaEE Trainers
 
Introduction to ejb and struts framework
s4al_com
 
Struts2
shankar_b7
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Struts notes
dssreenath
 

Similar to Struts 1 (20)

PPTX
struts unit best pdf for struts java.pptx
ozakamal8
 
PPTX
struts unit best pdf for struts java.pptx
ozakamal8
 
DOCX
Struts Interview Questions
jbashask
 
PPT
Strut2-Spring-Hibernate
Jay Shah
 
PPT
MVC
akshin
 
DOCX
Server side programming bt0083
Divyam Pateriya
 
PPT
Krazykoder struts2 intro
Krazy Koder
 
PDF
Struts2 tutorial
Achyuta Kumar
 
PDF
Struts2 tutorial
Suhas Kamble
 
PPT
Ibm
techbed
 
PPTX
Skillwise Struts.x
Skillwise Group
 
PPT
Struts2.x
Sandeep Rawat
 
PDF
Struts2 tutorial
izdihara
 
PPT
Struts N E W
patinijava
 
PDF
IRJET- Lightweight MVC Framework in PHP
IRJET Journal
 
PDF
Programming Jakarta Struts 1st Edition Chuck Cavaness
piqipixw4959
 
PDF
Struts tutorial
OPENLANE
 
PPT
Struts 2-overview2
divzi1913
 
DOCX
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
PPT
Struts
Ranjan Kumar
 
struts unit best pdf for struts java.pptx
ozakamal8
 
struts unit best pdf for struts java.pptx
ozakamal8
 
Struts Interview Questions
jbashask
 
Strut2-Spring-Hibernate
Jay Shah
 
MVC
akshin
 
Server side programming bt0083
Divyam Pateriya
 
Krazykoder struts2 intro
Krazy Koder
 
Struts2 tutorial
Achyuta Kumar
 
Struts2 tutorial
Suhas Kamble
 
Ibm
techbed
 
Skillwise Struts.x
Skillwise Group
 
Struts2.x
Sandeep Rawat
 
Struts2 tutorial
izdihara
 
Struts N E W
patinijava
 
IRJET- Lightweight MVC Framework in PHP
IRJET Journal
 
Programming Jakarta Struts 1st Edition Chuck Cavaness
piqipixw4959
 
Struts tutorial
OPENLANE
 
Struts 2-overview2
divzi1913
 
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
Struts
Ranjan Kumar
 
Ad

Recently uploaded (20)

PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Ad

Struts 1

  • 3. • MVC is a design pattern that facilitates development of scalable, flexible applications by segregating the application components into one of the following: Model View Controller
  • 4.  The model refers to those components of the application that do the major work done by the application.  In web application, models perform validation, implementation of web logic, write and read to and from the database.  The Model components majorly serve the following purpose:  Represent the business entities. Instances of the model are used to carry data around.  Encapsulate functionalities provided by the application- Database reading and writing validation etc.  Decide the flow of execution of the application. Usually the methods of the models decide the line of execution.
  • 5. Models are the engine of the application. They contain most of the code for what the application does. They are the busiest code in an application
  • 6.  View refers to the application’s face. It refers to that component or group of components with which the user interacts.  When a user accesses/interacts with a web application, he/she does it through web pages that are part of the web application. These pages constitute the view.  Views are generally used for the following purpose:  Representing data entry forms.  Representing reports-Tabular display of data.
  • 7. Views are like the control panel. They are interfaces through which data is entered. They also show results. Views are what the data users see and experience in a web application.
  • 8.  The controller’s primary task is to act like a router.  It moves data around the application in the form of objects of the model.  It is also responsible for initiating the execution of model’s methods.  After initiating the execution, the controller figures out the result of the execution and accordingly renders an appropriate view to the user.
  • 9. Controller is the wiring of the web application. Responsible mainly for data routing and also making the application run along a certain path of execution.
  • 11.  MVC pattern helps us achieve loose coupling by dividing the application into the model, view and controller components.  Since the model and controller are independent of the view, one view technology can easily swapped for the other, application is not very affected in case of such a view.
  • 13.  Implementation of the MVC pattern done by Apache Software Foundation.  Web application development framework.  Based on java technologies like Servlets, JSP, Java Beans  Present in two major flavors: • Version 1.x • Version 2.x Provides rich libraries that automate several tasks involved in developing web applications like AJAX, validation etc.
  • 14.  Developed by Craig McClanaghan  Donated to the Apache Software Foundation in the year 2000  Ever since had been used in numerous projects across the world and has been accepted as the web development framework of choice.  Early 2005, WebWork project spun off from struts framework.  WebWork and Struts merge together in Feb 2007 and remerged as struts 2.  Current Version 2.3.1
  • 15.  Struts is a java based MVC implementation.  Java technologies have been used in realizing the model, the view and the controller.  These components are implemented through the following:  Model-Action Classes(Simple classes also known as POJO’s)  View-JSP Pages  Controller-Servlet Filter
  • 16.  Models in Struts are normal Java classes.  These classes usually have properties to hold data. For instance the data posted by a form is held in an Action class via the member variables.  These classes also have methods that contain the business logic of the application like validation, saving data to database or retrieve data from the perspective of the application etc.  These methods may themselves do the task or call methods present in other classes, just to introduce modularity.  The methods return a string that represents the result of the activity performed by the method.
  • 17.  Action classes are simply java classes. So they need not extend or implement any class or interface as such.  There are classes and interfaces however in the Struts library that make the task of creating action classes a little simpler.  Often action classes may also inherit from either:  The Action interface  The ActionSupport class(which in turn implements the Action interface)  Inheriting from the Action interface or ActionSupport class provides utility functions for doing stock activities like validation etc.
  • 18.  let us proceed for building our first Hello World struts2 project.  The aim of this project is to build a web application that collects the user's name and displays "Hello World" followed by the user name.
  • 19. public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
  • 20.  Views are one of the most beautiful aspect of Struts framework.  Views are JSP pages.  Views may be forms or reports.  Struts provides a rich set of tags(struts-tags) that make creating forms and incorporating validation into them easier than plain JSP.  So, lets go ahead and create a file-HelloWorld.jsp in our project
  • 21. <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value="name"/> </body> </html>
  • 22. We also need to create one page “index.jsp”. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call the a defined method of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ 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>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action="hello"> <label for="name">Please enter your name</label><br/> <input type="text" name="name"/> <input type="submit" value="Say Hello"/> </form> </body> </html>
  • 23.  Finally comes the controller  Well very less often do we build controllers. The struts libraries provide us with a controller that does almost all that needs to be done.  The controller is a Servlet filter by the name: FilterDispatcher.  All that we need to do is configure the web app in such a manner that, all requests are routed through the FilterDispatcher.  The FilterDispatcher is configured using an xml configuration file that goes by the name struts.xml. Its contained in WEB-INF.  Primarily it contains the various possible outcomes of actions and the target the outcomes map to.
  • 24.  In order to configure the controller add the following code to the web.xml file. <?xml version="1.0" encoding="UTF-8"?> <web-app> <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> This would make sure all requests that are received by the web server are route through the filter(Controller).
  • 25.  We are almost done but there is one last thing that needs to be done i.e. wiring the action class up to the rest of the application.  Forms can easily submit data to JSP pages or servlets. In case we want the data to be submitted to an Action class, we need to route it through the FilterDispatcher.  The FilterDispatcher looks up the struts configuration file and decided which Action class has to be instantiated and whose method has to be called.  Configuration information related to Action classes are stored in the struts.xml file.  This file should be present in the same place where other classes are stored, i.e. /WEB-INF/classes.
  • 26.  Type the following code into the struts.xml file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts- 2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello“ class="com.tutorialspoint.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts>
  • 27.  Code mentioned in previous slide defines an action called HelloWorldAction.  For this action’s execute method, if the string “success” is returned then HelloWorld.jsp is dispatched to the client.  There can be more than one results of the action all defined within the action tag.
  • 28.  Finally the application can be deployed and executed.  Some error scenarios:  Tomcat startup errors may be due to:  Wrong data in struts.xml or web.xml  Incompatible jar files in the lib folder  Resource not found errors may be again due to the same reasons. So please check web.xml and struts.xml files.
  • 30.  One of the good things in Struts 2.x is that Action classes need not be special. They can be normal classes(classes that do not inherit any other class or interface)  You may however at times create Action classes by:  Inheriting the Action interface  Extending the ActionSupport class.  The action class also may have methods other than the execute method that can be invoked by the FilterDispatcher, provided its name is present in the struts.xml file.
  • 31.  Action classes that implement the Action interface inherit five variables:  public static final String SUCCESS=“success”  public static final String NONE=“none”  public static final String ERROR=“error”  public static final String INPUT=“input”  public static final String LOGIN=“login”  These variables are symbolic of what next should happen after the action class method is executed. They can be returned from the methods and appropriate mapping provided in the struts.xml file.
  • 32.  The following table lists the constants and their meanings: Result Meaning/Description SUCCESS The action was successful. NONE The action was successful but do not show a view. ERROR The execution failed. INPUT The action requires more input before it can be executed. LOGIN The action could not be completed as the user is not logged in.
  • 33.  The Action interface also contains the definition of the execute method: Public String execute() throws Exception  So in case you are implementing this interface to create the action class, you need to override this method.  It’s a good practice to implement this interface because that way we can be sure that our class contains an execute() method.  There is a disadvantage however. To compile such a class, the classpath needs to be set to point to the jar file that contains the Action interface.
  • 34.  The ActionSupport class implements the Action interface and provides blank implementation for the execute() method.  Apart from Action, the ActionSupport class also implements the following interface:  Validateable  ValidationAware  TextProvider  LocaleProvider  Serializable
  • 35.  This interface contains the validate() method. The definition is:  Public void validate()  A blank implementation is provided in the ActionSupport class.  In our Action classes, this is where validation of the values should be done.
  • 36.  This interface contains an assortment of methods that a class should have if its capable of storing validation messages. Few of the methods are:  addActionError(String message)-This function is called to log an error message for the action.  addActionMessage(String message)-Log a message for this action.  Collection<String> getActionErrors()-Retrieves the error messages for this action. Can be used in views to retrieve the error messages that were logged related to the action.  Collection<String> getActionMessages()-Retrieves the messages for this action.
  • 37.  addFieldError(String FieldName, String message)- This method adds an error message for a particular field. Useful when we want to show message in the form for fields.  Map<String, List<String>> getFieldErrors – This method returns the error messages logged for the various fields. Again used in views to retrieve the error messages for individual fields.
  • 38.  These interfaces provide support for globalization and localization.  The TextProvider interface has method for loading resource bundles. The actual implementation has to be provided by the inheriting class.  The LocaleProvider interface has methods to retrieve current locale. Again the actual implementation has to be provided by the inheriting class.
  • 39.  The Serializable interface allows for persisting the action class instances to streams.  Particularly useful if the objects data has to be persisted to files rather than to the database management system.
  • 40.  import com.opensymphony.xwork2.ActionSupport; public class Login extends ActionSupport{ String username ,password; // Getters and Setters public void validate() { if(username==null||username.length()==0) addFieldError(“username”, ”Username cannot be left empty, please enter valid username”); if(password==null||password.length()==0) addFieldError(“password”, ”Password cannot be left empty , please enter valid username”); } public String execute() { return “success”; } }
  • 41.  Understanding the advantages of MVC pattern for designing application.  Clearly understand the advantages of using the Struts 2.x for building web applications  Understand the usage of Model, View and Controller components of Struts 2.x framework.  Build web applications that use the features of Struts 2.x framework