SlideShare uma empresa Scribd logo
1 de 42
STRUTS2.x
• 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.
 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.
 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.
 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
STRUTS2.x MVC Framework Explained

Mais conteúdo relacionado

Mais procurados

Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overviewskill-guru
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Applicationelliando dias
 
Struts(mrsurwar) ppt
Struts(mrsurwar) pptStruts(mrsurwar) ppt
Struts(mrsurwar) pptmrsurwar
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 FrameworkEmprovise
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issuesPrashant Seth
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
important struts interview questions
important struts interview questionsimportant struts interview questions
important struts interview questionssurendray
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsJavaEE Trainers
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts frameworks4al_com
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 

Mais procurados (20)

Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overview
 
Struts introduction
Struts introductionStruts introduction
Struts introduction
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Application
 
Struts course material
Struts course materialStruts course material
Struts course material
 
Struts(mrsurwar) ppt
Struts(mrsurwar) pptStruts(mrsurwar) ppt
Struts(mrsurwar) ppt
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Struts presentation
Struts presentationStruts presentation
Struts presentation
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Struts2
Struts2Struts2
Struts2
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issues
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
Struts2
Struts2Struts2
Struts2
 
important struts interview questions
important struts interview questionsimportant struts interview questions
important struts interview questions
 
Struts framework
Struts frameworkStruts framework
Struts framework
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web Applications
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 
Struts2
Struts2Struts2
Struts2
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Struts notes
Struts notesStruts notes
Struts notes
 

Semelhante a STRUTS2.x MVC Framework Explained

Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questionsjbashask
 
Strut2-Spring-Hibernate
Strut2-Spring-HibernateStrut2-Spring-Hibernate
Strut2-Spring-HibernateJay Shah
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Krazykoder struts2 intro
Krazykoder struts2 introKrazykoder struts2 intro
Krazykoder struts2 introKrazy Koder
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorializdihara
 
IRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHPIRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHPIRJET Journal
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorialOPENLANE
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2Santosh Singh Paliwal
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 

Semelhante a STRUTS2.x MVC Framework Explained (20)

Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questions
 
Strut2-Spring-Hibernate
Strut2-Spring-HibernateStrut2-Spring-Hibernate
Strut2-Spring-Hibernate
 
MVC
MVCMVC
MVC
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Krazykoder struts2 intro
Krazykoder struts2 introKrazykoder struts2 intro
Krazykoder struts2 intro
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Ibm
IbmIbm
Ibm
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 
IRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHPIRJET- Lightweight MVC Framework in PHP
IRJET- Lightweight MVC Framework in PHP
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorial
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Struts
StrutsStruts
Struts
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

STRUTS2.x MVC Framework Explained

  • 2.
  • 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.
  • 10.
  • 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.
  • 12.
  • 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.
  • 29.
  • 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