Struts-config.xml file

advertisement
STRUTS 1.3.10
1)chapter-I
Framework:
struts1.x features
comparison between servlets and Struts
--------------------------------------------------2)chapter-II
MVC
MVC-2
--------------------------------------------------Design Patterns
--------------------------------------------------3)chapter-III
Complete Struts Architecture (request flow)
----------------------------------------------------------------------------------------------------SERVER-SIDE validation Framework
--------------------------------------------------4)chapter-IV
ActionForm
DynaActionForm
ValidatorForm
DynaValidatorForm
ValidatorActionForm
DynaValidatorActionForm
---------------------------------------------------
Controller classes(CommandPattern)
-------------------------------------------------5)chapter-V
Action
DispatchAction
LookupDispatchAction
MappingDispatchAction
EventDispatchAction
--------------------------------------------------
6)chapter-VI
i18n,l10n
LocaleACtion
--------------------------------------------------
7)chapter-VII
LocalForwards(foreach),GlobalForwards(forall)
LocalExceptions(foreach),GlobalExceptions(forall)
-------------------------------------------------8)chapter-VIII
Modularization(foreach module separate config.xml):
SwitchAction(communicator-between modules)
--------------------------------------------------9)chapter-IX
TILES FRAMEWORK:
--------------------------------------------------10)chapter-X
PlugIn classes implementation
Introduction:
Struts is a open source framework for building JAVA based web applications. Struts introduced by
apache foundation. It was originally created by Craig McClanahan and donated to the Apache
Foundation in May, 2000. Formerly located under the Apache Jakarta Project and known as Jakarta
Struts, it became a top-level Apache project in 2005.
Struts Major Released Versions:
Struts 1. x:june 2001
Struts 2.x: February 2007
Struts Features :
1. Struts is a open source Framework. If Developer wants to change struts flow of execution it
will allow us to change .
2. Easy to Understand . For the struts development they are using Servlet's and jsp's
3. Struts will Reduces the development time& cost in developing j2ee web applications
4. Struts using XML dynamic configurations(struts-config.xml) .This feature allows developer to
change configurations dynamically for the future modifications so developer no need to
change java code and no need to compile again and again
5. Developer need not to concentrate on servlets coding insted of that they should focus on
Model classes development .Model classes are (ejb session beans and entity beans.(or)Spring
configured business classes and Hibernate Dao's)
6. Struts following complete MVC base architecture so the code division is easy
7. Struts providing server side form validation support by using ActionForm classes and
validation.xml validation framework simply using java based regular expressions. Easy plug-in
support .
8. Restore Form view Support
9. Struts following front controller pattern that's the reason why container will create only single
instance of a Front Controller servlet for the complete application. For a Web Application only
single servlet instance will create.
10. Built-in Internationalization support ,Localization support.
11. By using struts we can provide well designed UI by using struts tags like text boxes,
checkboxes, radio buttons dynamic drop down list ,page layouts can create by using tiles
12. Declarative Exception Handling( when exception rise in controller we can handle and redirect
error pages instead of printing exception stack)
13. Easy Pluggable Features (integrating with ejb2.0,spring,hibernate)
14. Modularization
Servlets and JSP's:
Before going to struts world just have a look at servlets/jsp .
Servlets follows MVC jsp model1 architecture.
Servlets are the server side components to develop Dynamic web applications there we need
to fallow directory structure to develop and deploy web application. servlets can read form
parameters from the input html/jsp files after reading parameters we have to perform business
validations, business operations and Database operations .After completion of development we have
to deploy it into web application server and we should test it. Servlets can provide features like
session management and user defined response page to the client. And developer can provide
dynamic configuration parameters by using init and context parameters to servlets and by giving load
on startup we can create instances at the time of deployment itself. And we can redirect request
parameters to one servlet to another servlet .We can provide dynamic response page to the client.
and we have Listeners and Filters Support.
JSP's and Servlets follows MVC jsp model2,jsp model2,model3,model4 architecture
Jsp are the Dynamic web page components we can provide dynamic pages by using this java
servlet pages .Dynamic compilation will happens on server we we make any changes in our jsp pages.
jsp's are providing custom tags to reduce coding. and we can populate dynamic parameters by using
use bean tags.
MVC architectures:
MVC stands for Model View Controller
View components are Html pages, jsp pages, .js ,. cs files
Controller classes are Servlets and Jsp pic's
Model classes are Dao's Data Access Objects
MVC(Model-View-Controller)
View
HTML/JSP
Controller
Servlet/JSP/Filter/
Custom Tags
Model
DAO
DataAccessObject
Sub Models of MVC:
i.
ii.
iii.
iv.
If You use Servlet as a controller Then it is MVC jspmodel1 architecture
If You use JSP as a controller Then it is MVC jspmodel2 architecture
If You use Filter as a controller Then it is MVC jspmodel3 architecture
If You use Custom Tags as a controller Then it is MVC jspmodel4 architecture
MVC2(Model-View-Business logic-Model)
View
HTML/JSP
Controller
Servlet/JSP/Filter/
Custom Tags
Business Logic
JAVA class
DAO
DataAccessObject
Welcome to Struts
We have already servlets for building a web application then why we need to go for Frameworks.
The reasons are, look at Struts Features : above given
Framework: Framework is A Semi Developed Application for building some kind of Architecture
approached Applications.
Struts Framework: Struts is A Semi Developed Application for MVC Kind of Applications Struts
Fallowing Design pattern principles for Building Dynamic Web Application
Design patterns:
In software engineering, a design pattern is a general reusable solution to a commonly occurring
problem within a given context in software design.
which problems we find when we are building web applications by using servlets
1.
For each and every input form we need write one one servlet . so if our application have 100
we have to write 100 servlets
forms
2.
Form redirections and Exception page redirections we should give inside the servlet coding .If you
want to change them in future we have to recompile the code so it is hard to maintenance
team and
deployment team
3.
If JavaScript disables in user browsers window we have to write server side field validation and we
should send same kind of error message every time or multiple validation error pages we
should
redirect
4.
To reduce no of pages developer must have knowledge on Ajax
5.
Inside jsp pages it self we need to configure includes and forwards so if you want to change view
in future we should make changes in our jsp pages
So which design patterns will help us to solve these problems
a)
b)
c)
d)
e)
Front Controller
Application Controller
View Helper
Command pattern
Composite View
a)Front Controller:
Single Servlet receives Request coming from the multiple View Files jsp/html
b)Application Controller:
Front Controller Delegated Controller Class
c)View Helper:
Both I/p and O/p views are stored in a single Bean class
d)Command Pattern:
Classes which takes action for submit button
e)Composite View:
When multiple views combined into another view mechanism is called Composite View pattern
Struts Architecture
Struts1.3.10
web.xml
struts-config.xml
(1)
INPUT Form
INPUT Form
INPUT Form
OUTPUT Form
S
E
R
V
E
R
ActionServlet (2)
(3)
(4)
(4)
doPost (5)
process
Request Processor
OUTPUT Form
OUTPUT Form
(6)
PRESENTATION
(or)
VIEW
Init
doGet
doPost
process(5)
Init
preProcess
process
(7)
ActionForm
Action
validate()
execute()
reset()
(8)
Service
CONTROLLER
Dao
(9)
MODEL
(10)
Struts Request Flow:
i.
ii.
iii.
iv.
v.
vi.
vii.
viii.
ix.
x.
xi.
xii.
xiii.
xiv.
xv.
xvi.
At deployment time or at First User request Container will create ActionServlet
New Instance and it will call init (in web.xml file have to configure it with *.do url
pattern)
Init method will read struts xml and it will store that information into ModuleConfig
config reference and
When user request initModuleFormBeans(ModuleConfig config) will create form bean
instance and it will keep it in scope(request or session)
When user request container will send that request to doGet or doPost methods
Form doGet (or) doPost it will deligate to process method of ActionServlet
Process method of ActionServlet will create one Singleton Instance of A
RequestPorcessor and call init method of Request processor
Here we should note one thing for Each and Every module ActionServlet will create
one RequestProcessor object that means (for Entair application one ActionServlet and
no..of RequestProcessors its depends one no..of modules EX: 3 modules =3 Request
processors)
ActionServlet process method will delegate request to RequestProcessor process
method
RequestProcessor Process method will call preProcess method Of same class, here
preProcess method return type is Boolean if preProcess method returns true then only
process method will do remaining process other wise it will not process the request to
next level(note: Default RequestProcessor preProcess default implementation return
value is true)
RequestProcessor process method will populate read user input form data and
populates that form data into ActionForm instance by calling setter methods
Then next it will call validate method for validations it will return ActionErrors object
this ActionErrors is the subclass of ActionMessages
In ActionMessages class isEmpty method is there it will check error messages what we
added in our conditions (if(name.equals("")){ae.add("name",new
ActionMessage("mgs"));})
If count is zero then process method will redirect input page to the User For populating
error messages
If error count is not equals to zero the process method will create ActionClass object
In singleton factor (for first user request) the it will call execute method Of our
Controller class
For that execute method It pass( ActionMapping,ActionForm,HttpServletRequest,
HttpServletResponse) as execute method parameters
By using request or actionform parameter we can read form data to process next
Model layer classes
xvii.
From execute method RequestProcessor process method expect one ActionFoward
return type in that actionForward we can configure required page redirection
configuration
xviii. Based on that configuration Process method will forward required configured page
what we have configured under struts-config.xml file <forward > tag
Struts-config.xml file tags and info
Configuring ActionServlet in web.xml
This is struts front controller Servlet that receives every
<!-- Standard Action Servlet Configuration -->
form request coming to struts and process the request.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
Passing struts-config.xml file into ActionServlet as init-param
</servlet>
AtionServlet instantiates at the time
of server startup
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
url-pattern is configured to *.do, hence every action path
coming to struts must end .do extension
Connection pools can be configured in struts in this tag. For each DB we need to configure
one data-source tag here. But struts recommends not to configure connection pool here
because we need to write model layer separately and there we need to configure CPM.
For instance do CPM in hibernate. IN struts 1.3 this tag is removed.
Struts-config.xml file
<struts-config>
<data-sources>
<data-source>
ActionForm classes are configured here. For every JSP we need
</data-source>
to write one ActionForm class.
</data-sources>
<form-beans>
<form-bean name=”laf” type=”beans.LoginActionForm”>
</form-bean>
<form-bean name=”daf” type=”org.apache.struts.action.DynaActionForm”>
<form-property property=”user” type=”java.lang.String”/>
<form-property property=”pass” type=”java.lang.String”/>
</form-bean>
Exceptions which are raised commonly in more than one Action
</form-beans>
class are configured here.
<global-exceptions>
<exception type=”java.sql.SQLException” key=”error.sql” scope=”request”
path=”/SQLError.jsp”>
</exception>
<exception type=”java.lang.NullPointerException” key=”error.null” scope=”request”
path=”/NullError.jsp”>
</exception>
Forwards which are returned commonly from more than one
</global-exceptions>
Action class are configured here.
<global-forwards>
<forward name=”HOME” path=”/index.jsp” redirect=”true”>response.sendRedirect() is used
</forward>
<forward name=”LOGIN” path=”/login.jsp” redirect=”false”>RequestDispatcher.forward() is used
</forward>
For every form we will configure one Action class that
</global- forwards> action class and entire struts flow is configured here.
<action-mappings>
<action path=”/login” name=”laf” scope=”session|request” validate=”true|false”
input=”/Login.jsp” type=”beans.LoginAction” parameter=”used in Dispatch Actions”>
<forward name=”SUCCESS” path=”/MainMenu.jsp”></forward>
<exception></exception>
</action>
</ action-mappings>
<controller>
<set-property property=”processorClass” value=”org.apache.struts.action.requestProcessor”>
</set-property>
ActionServlet by default uses this
RequestProcessor hence we need not
</controller>
have to configure this class. Configure if
<message-resources parameter=”beans.ApplicationResources”>
our own RequestProcessor is written.
</message-resources>
<plug-in className=”org.apache.struts.validator.ValidatorPlugin”>
<set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml, /WEBINF/validation.xml”></set-property>
This plug-in is configured for validation framework
</plug-in>
<plug-in className=”org.apache.struts.tiles.TilesPlugin”>
<set-property property=”definitions-config” value=”/WEB-INF/tiles-defs.xml”></set-property>
</plug-in>
This plug-in is configured for Tiles framework
</struts-config>
About struts tag libraries
<%@ taglib uri=”http://struts.apache.org/tags-bean” prefix=”bean”%>
This tag library contains tags useful in accessing beans and their properties, as well as defining new beans
(based on these accesses) that are accessible to the remainder of the page via scripting variables and page
scope attributes.
Tag name
Include
Message
Page
Resource
Size
Struts
Tag description
Load the response from a dynamic application request and make it available as a bean
Render an internationalized message string to the response
Expose a specified item from the page context as a bean
Load a web application resource and make it available as a bean
Define a bean containing the number of elements in a Collection or Map
Expose a named Struts internal configuration object as a bean
<%@ taglib uri=”http://struts.apache.org/tags-html” prefix=”html”%>
This taglib contains tags used to create struts input forms, as well as other tags generally useful in the creation
of HTML-based user interfaces.
Tag Name
Base
Button
Cancel
checkbox
Errors
File
Form
Frame
Hidden
Html
Image
Img
javascript
Link
messages
Multibox
Tag Description
This tag contains href attribute that contains path of the base directory of the current
page..Suppose in current document if images or js file or css file or any other anchor tags
exist we can directly give file namepath will be automatically from base tag href attribute.
A Button Input Field Renders an HTML <input> element of type button
Render a Cancel Button Renders an HTML <input> element of type cancel
Render A Checkbox Input Field Renders an HTML <input> element of type checkbox,
populated from the specified value or the specified property of the bean associated with
our current form
Conditionally display a set of accumulated error messages
Render A File Select Input Field Renders an HTML <input> element of type file, defaulting
to the specified value or the specified property of the bean associated with our current
form
Define An Input Form Renders an HTML <form> element whose contents are described by
the body content of this tag
Render an HTML frame element Renders an HTML <frame> element with processing for
the src attribute that is identical to that performed by the <html:link> tag for the href
attribute
Render A Hidden Field Renders an HTML <input> element of type hidden, populated from
the specified value or the specified property of the bean associated with our current form
Element Renders an HTML <html> element with language attributes extracted from the
user's current Locale object, if there is one
Render an input tag of type "image" Renders an HTML <input> tag of type "image"
Render JavaScript validation based on the validation rules loaded by the ValidatorPlugIn
Renders an HTML <a> element as an anchor definition (if "linkName" is specified) or as a
hyperlink to the specified URL
Conditionally display a set of accumulated messages
Renders an HTML <input> element of type checkbox, whose "checked" status is initialized
based on whether the specified value matches one of the elements of the underlying
property's array of current values
Option
Render an HTML <option> element, representing one of the choices for an enclosing
<select> element
Options
Render a Collection of Select Options Renders a set of HTML <option> elements,
representing possible choices for a <select> element
optionsCollection Render a Collection of Select Options Renders a set of HTML <option> elements,
representing possible choices for a <select> element
Param
Adds a parameter to the following tags: <html:frame> <html:link> <html:rewrite> Since:
Struts 1
password
Render A Password Input Field Renders an HTML <input> element of type password,
populated from the specified value or the specified property of the bean associated with
our current form
Radio
Render A Radio Button Input Field Renders an HTML <input> element of type radio,
populated from the specified property of the bean associated with our current form
Reset
Render A Reset Button Input Field Renders an HTML <input> element of type reset
Rewrite
Render an URI Renders a request URI based on exactly the same rules as the link tag does,
but without creating the <a> hyperlink
Select
Render A Select Element Renders an HTML <select> element, associated with a bean
property specified by our attributes
Submit
Render A Submit Button Renders an HTML <input> element of type submit If a graphical
button is needed (a button with an image), then the image tag is more appropriate
Text
Render An Input Field of Type text Render an input button of type text
Textarea
Render A Textarea Render a textarea element
Xhtml
Render HTML tags as XHTML Using this tag in a page tells all other html taglib tags to
render themselves as XHTML 1
<%@ taglib uri=”http://struts.apache.org/tags-logic” prefix=”logic”%>
<p>This tag library contains tags that are useful in managing conditional generation of output text, looping over
object collections for repetitive generation of output text, and application flow management.</p> <p>For tags
that do value comparisons (equal, greaterEqual, greaterThan, lessEqual, lessThan, notEqual), the following rules
apply:</p> <ul> <li>The specified value is examined.
Tag Name
Forward
Iterate
Match
Tag Description
Forward controls to the page specified by the specific ActionForward Entry
Repeat the nested body content of this tag over a specified collection
Evaluate the nested body content of this tag if the specified value is an appropriate
substring of the requested variable
messageNotPresent Generate the nested body content of this tag if the specified message is not present in
this request
messagePresent
Generate the nested body content of this tag if the specified message is present in this
request
notMatch
Evaluate the nested body content of this tag if the specified value is not an appropriate
substring of the requested variable
notPresent
Generate the nested body content of this tag if the specified value is not present in this
request
Present
Redirect
Generate the nested body content of this tag if the specified value is present in this
request
Render an HTTP Redirect Performs an HttpServletResponse
<%@ taglib uri=”http://struts.apache.org/tags-tiles” prefix=”tiles”%>
Tag Name
Tag Description
Add
Add an element to the surrounding list
Definition
Create a tile /component / template definition bean
Get
Gets the content from request scope that was put there by a put tag
getAsString
Render the value of the specified tile/component/template attribute to the
current JspWriter Retrieve the value of the specified tile/component/template
attribute property, and render it to the current JspWriter as a String
importAttribute
Import Tile's attribute in specified context
initComponentDefinitions Initialize Tile/Component definitions factory
Insert
Insert a tiles/component/template
Put
Put an attribute into tile/component/template context
putList
Declare a list that will be pass as attribute to tile
useAttribute
Use attribute value inside page
Explanation of core components of Struts Architecture
ActionServlet
ActionServlet is a front controller Servlet in Struts and the only Servlet exist in Struts framework. Every request
coming to Struts must first come to ActionServlet class instance. When ActionServlet class init() method
executes, ActionServlet reads struts-config.xml file data and stores it into one ModuleConfig class object.
ModuleConfig class object contains all 8 struts-config.xml file elements. Once after moduleConfig object is
created that object is passed into one new instance of RequestProcessor class constructor.
RequestProcessor rp=new RequestProcessor(this, mc)
This is current ActionServlet class instance and mc is ModuleConfig class object.
ActionServlet
Init(){
//form bean,exception handlers,plugin initialization
}
doGet(req,res){
process(req,res);
}
doPost(req,res){
process(req,res);
}
Process(req,res){
RequestProcess
rp=RequestProcessUtil.getInstance(ModuleConfig mc);
Rp.process(req,res);
}
}
struts-config.xml
<form-beans>
<global-exceptions>
<global-forwards>
<action-mappings>
<controller>
<mapping-resources>
<plug-in>
public class RequestProcessor extends Object {
public void init(ActionServlet as, ModuleConfig mc) {}
public void process(HSR req, HSR response) throws E {
processMultipart();
processPath();
processLocale();
processContent();
processNoCache();
processPreprocess();
processCachedMessages();
processMapping ();
processRoles();
processActionForm();
processPopulate();
processValidate();
processForward(); / processInclude();
processActionCreate();
processForwardConfig();
}}
In the process() method ActionServlet invokes process() method RequestProcessor class instance.
RequestProcessor class further process form request.
ModuleConfig
ModuleConfig contains struts-config.xml file content. It contain all ActionForm, Action, ActonForward,
ActionMapping class names. Whenever client request comes ActionServlet sends request to RequestProcessor,
RequestProcessor uses ModuleConfig object to findout the ActionForm and Action class names of the
requested action path uri.
Some important methods are:
 getActionFormBeanClass()
 getActionMappingClass()
 addActionConfig()
 addDataSourceConfig()
 addExceptionConfig()
 addFormBeanConfig()
 getActionForwardClass()
 addForwardConfig()
 addMessageResourcesConfig()
 addPlugInConfig()
 findActionConfig()
 findActionConfigs()
 findExceptionConfig()
 findFormBeanConfig()
 findForwardConfig()
 findMessageResourcesConfig()
 findPlugInConfigs()
RequestProcessor
RequestProcessor class is called as ApplicationController and ActionServlet is called as FrontController.
Whenever client request comes ActionServlet delegates request processing to RequestProcessor only. The
methods of RequestProcessor class are given above. If developer want to change the struts flow of execution
then processPreprocess() method must be overridden.
ActionForm
ActionForm class is a Java Bean in struts framework. For every JSP request developer write one ActionForm
class that must extend from ActionForm. In this class developer must declare all form properties as private and
for each private property one pair of public set and get method must be implemented and also override
validate() method. In validate() method developer can write create object of ActionMessage for each field and
all such ActionMessage objects must be added to ActionErrors using property name. Developer can also
override reset() method. In the reset() method if all class instance variables are initialized to null or default
values, then when form is forwarded back to browser the previous form data may not be restored on that
form. If reset() method is not overridden then form restoration takesplace.
ActionMapping
ActionMapping class contains <action> tag data. Whenever ActionServlet reads struts-config.xml file it stores
each action tag attributes into one ActionMapping class object. <action> tag contains path, name, scope,
validate, input, type and parameter attributes. All these attributes are stored in ActionMapping class object
hence ActionMapping class contains one pair of set and get method to access and modify each attribute.
Some important method are:
 setPath(String path)
 getPath()
 setName(String name)
 getName()
 setScope(String scope)
 getScope()
 setValidate(boolean flag)
 getValidate()
 setInput(String input)
 getInput()
 setType(String actionClassName)
 getType()
 setParameter(String parameter)
 getParameter()
 findForward(String name)
 findForwards()
ActionErrors
ActionErrors class is a sub class of ActionMessages. This class is having only one method. validate() method of
ActionForm returns this class object only to RequestProcessor and RP forward input JSP to browser. By default
struts stores this class object into request scope with the attribute name Globals.ERROR_KEY. In JSP
<html:errors> tag reads all ActionError/Message objects from this object only using properties and displays
error messages on browser.
 add(String propertyName, ActionError am)
ActionError/ActionMessage
ActionMessage class is a sub class of Serializable interface. This class is having following methods
 ActionMessage(String key)
 ActionMessage(String key, Object value0)
 ActionMessage(String key, Object value0, Object value1)
 ActionMessage(String key, Object value0, Object value1, Object value2)
 ActionMessage(String key, Object value0, Object value1, Object value2, Object value3)
 ActionMessage(String key, Object[] values)
ActionError is a sub class of ActionMessage, hence this class also contains the same number of constrctors.
Action
Developer must implement for processing in this class only. This class contains execute() method. This method
takes 4 arguments.
 ActionForward execute(ActionMapping am, ActionForm af, HttpServletRequest req,
HttpServletResponse resp)
 generateToken(HttpServletRequest)
 saveToken(HttpServletRequest)
 isTokenValid (HttpServletRequest)
 resetToken(HttpServletRequest req)
 saveErrors(HttpServletRequest req, ActionMessages errors)
 saveMessages(HttpServletRequest req, ActionMessages errors)
ActionForward
The return type of execute() method of Action class is ActionForward object only. Whenever we write <forward
name=”SUCCESS” path=”/LoginSuccess.jsp” redirect=”false”/>, the tag is stored in this class object only. In the
execute() method we will perform some form processing and write am.findForward(“SUCCESS”) that method
returns this ActionForward object only.
Directory Structure
Of struts web project
Struts1.3.x Application examples:
For doing Struts1.3 examples you need add struts library given in struts1.3 jar have to configure in class path
download struts lib files from
http://struts.apache.org/download.cgi
JRE:
1.3 and above compatibility
Hello World example:
Note:
If we create input form by using struts tags then have to write 2 classes
Else one class is enough
+Open Eclipse:
i.
ii.
iii.
Create New Dynamic web project:
Project Name :Hello_APP
Create struts-config.xml file under WEB-INF folder
iv.
Add jar files (servlet-api.jar,struts1.3.10 api jar files)
v.
Open web.xml file
vi.
Open index.jsp create a simple hello form
vii.
Write one action class under src
HelloController.java
viii.
Open struts-config.xml configure it
ix.
Open success.jsp
x.
Deploy into tomcat
Right click on project select run on server
Screen1
Pass name click on button
Screen2
chapter-IV
Validations
S
ecurity and data integrity are absolute priorities that any serious Computer
Program must ensure at some level. In our Web Applications we constantly deal with
information in high levels of importance and we simply can’t let corrupted data get into our
database.
In general there are 3 types of validations those are
i.
Client side validations(1st level)
ii.
Server side validations(2nd level)
iii.
Business validations(3rd level)
i.1st Level(Client-side):
We can apply these type validations to web applications input fields . In
html, jsp pages by using JavaScript
ii.2nd Level(Application-level):
We can apply these type validations to web applications input
fields In Filters by using simple conditions Regular Expressions
iii. 3rd Level(Database level): We can apply these type validations to web applications Input fields in
Dao classes
By using Struts we can provide 2nd Level validations In 2 ways
i.
Programmatic
ii.
Declarative( using XML files)
Programmatic Validations
For doing Programmatic Validations we have 2 classes
i.
ActionForm
ii.
DynaActionForm
ActionForm Example:
i.
Create a form By using struts tags
ii.
Write a validation class
iii.
Configure error messages in a properties file
iv. Write a Controller class
v.
Configure validation configurations and Controller Configurations Under struts-conig.xml file
+Open Eclipse
i.
Create Dynamicwebproject
ProjectName: RegForm
ii.
Create index.jsp:
iii.
Create success.jsp:
iv.
Create validation class under a package com.durgasoft.regform.web
RegForm.java
v.
Create a Properties File for configuring Error Messages
Create a package MyResources
Create one Messages.properties file
vi.
Create a Controller class under a package com.durgasoft.regform.web
vii.
Create a web.xml file under WEB-INF
viii.
Create a struts-config.xml under WEB-INF(copy dtd on top this code)
ix.
Run this project
Click on Register button
Note: If you use plain html tags for form creation no need to write private variables and public getters
and setters in your validation form bean class
DynaActionForm Example:
i.
Create a form By using struts tags
ii.
Write a validation class (only validate method with out private properties and public
getters and setters)
iii.
Configure error messages in a properties file
iv.
Write a Controller class
v.
Configure validation configurations and Controller Configurations Under struts-conig.xml
file
+Open Eclipse
vi.
Create Dynamicwebproject
ProjectName: RegForm_DAF
vii.
Create index.jsp:
viii.
Create success.jsp:
ix.
Create validation class under a package com.durgasoft.regform.web
RegForm.java
x.
Create a Properties File for configuring Error Messages
Create a package MyResources
Create one Messages.properties file
xi.
Create a Controller class under a package com.durgasoft.regform.web
xii.
Create a web.xml file under WEB-INF
Copy above example web.xml file
xiii.
Create a struts-config.xml under WEB-INF(copy dtd on top this code)
xiv.
Run this project
Click on Register button
Fill & submit you will get success page
Declarative Validations
to avoid programmatic validations here they given declarative validations by using xml
files we can apply these kind of validations
Struts given 26 predefined set of validations under validator-rules.xml file which is there in
org.apache.struts.validator package . by using these predefined validation rules we can apply
validation for our input form fields
So here we should create one validation.xml file for applying validation for our input form
Like:
There are predefined validation like required,email,intRange.If it is programmatic a validate
method have to override and in that method we can apply required validation condition by using
if control statement
But through XML file how to add the same kind of conditions
<filed property=”name” depends=”required”><!—condition applying here-->
<arg key=”name”/> <!—argument passing to predefined error msg-->
</field>
<filed property=”email” depends=”required,email”>
<!—multiple condition applying here for only email field-->
<arg key=”email”/>
</field>
In this way we can able to apply ApplicationLevel validations by using validation.xml file
There are 4 classes for apply validations for input form fields
i.
ii.
iii.
iv.
ValidatorForm
DynaValidatorForm
ValidatorActionForm
DynaValidatorActionForm
i.
ValidatorForm example:
Here for convenient I am using MyEclips IDE
+OpenMyEclipse
go to file
create new webproject
name:RegForm_VF click on Finish
->right click on project
->go to myclipse option
->add struts capabilitys
select struts specification struts1.3
default application resource write Messages
click on finish
(by default It will add web.xml along with front controller configuration & it will
generate one default struts-config.xml
and required jar file also it will add)
+right click on WEB-INF
create new Files validation.xml,validation-rules.xml
go to struts-core.jar file
find validator-rules.xml file in org.apache.struts.validator package
copy complete content and paste it in your validator-rules.xml
copy 14 error message and paste in your Messages.properties file
copy plugin tag change location form validator package WEB-INF
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
paste this content under struts-config.xml file after <message-resource> tag
ii.
Open index.jsp write this sample
iii.
Open success.jsp write sample
iv.
Open RegForm write sample
v.
Open RegController write sample
vi.
Open validation.xml file write sample
vii.
Open struts-config.xml file write sample
viii.
Open Messages.properties
ix.
Click Register
ii.DynaValidatorForm:
DynaValidatorForm is a Built in FormBean class in struts lib we can use this DynaValidatorForm to store our
form properties and for applying validations with out writing any subclass directly we can consume it
The major dis-advantage of validator form is we have to Create A form along with private
properties and public getters and setters where as DynaValidatorForm is providing dynamic
variable declaration feature In struts-config.xml and dynamic validations under validation.xml
Ex:
Create dynamic web project
Name : RegForm_DVF
add capabilities’ like above example. And copy paste input,output pages in web root and
validation.xml,validation-rules.xml,struts-config.xml,web.xml into WEB-INF and Messages.properties
files,Controller class into src
Here no more formbean classes so no need to write any validation class
Make changes in struts-config.xml file
iii.ValidatorActionForm:
Here it is extention to validatorForm. The major difference is for multiple forms multiple Formbeans
have to write in case of ValidatorForm .The major advantage in validaotorActionForm and
DynaValidatorActionForm is we can consume single formbean form multiple input forms.
For example If we have one employeereg page(name,email,sal) and studentreg(name,email,marks)
page ,For these two input forms only one single formbean implementation is enough
Ex:
Create Dynamicweb project
Name: RegForm_VAF
Open index.jsp Write code
Open index1.jsp Write code
Open success.jsp write code
Open validation.xml file
openMessages.properties fill these properties
Open struts-config.xml file
Open RegForm write sample
Open RegController write sample
Deployee and Execute
Open Browser change language to US English Test it
Open Browser change language to IN English Test it
iv.DynaValidatorActionForm:
DynaValidatorActionForm will provide Features like ValidatorActionForm The defference here is DynamicForm
bean Configurations with out FormBean class
EX:
CreateDynamicweb project
Name: RegForm_DVAF
Add struts1.3 capabilities’
Copy RegController into src,validation.xml,validator-rules.xml,struts-config.xml,web.xml into WEB-INF
Copy Messages properties into scr ,copy input,output pages into webroot
No more FormBean class here Dynamic Formbean class we can consume
Open struts-config.xml file write configurations
TEST this application also in US English and India English both index.jsp and index1.jsp
****THANK YOU*******
INTERNATIONALIZATION
I18N
is the short hand name for Internationalization in between I---N This word having 18
character thats way we can call with short hand name.
In simple word i18n is a marketing technique to deliver their products into multiple regions
We can make our software products also by applying i18n.
Then any region people can consume by selecting their required language.
By using struts we can apply i18n in easy manner
For i18n support we have one tag library bean tags by using these bean tags we can read data from
particular language properties file
And To provide customized hyperlinks here we have one built in action class
LocaleAction
Ex:Create web project
Add struts1.3 capabilities
Open index.jsp page
Create multiple languages properties file in src
Messages.propties(for English)
Messages_te.properties
Messages_hi.properties
Open struts-config.xml file
Validation.xml :
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">
<form-validation>
<formset>
<form name="rf">
<field property="name" depends="required">
<arg key="name"/>
</field>
<field property="email" depends="required,email">
<arg key="email"/>
</field>
<field property="address" depends="required">
<arg key="address"/>
</field>
<field property="age" depends="intRange">
<arg key="age"/>
<var>
<var-name>min</var-name>
<var-value>1</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>100</var-value>
</var>
</field>
</form>
</formset>
<!-- hindi -->
<formset language="hi">
<form name="rf">
<field property="name" depends="required">
<arg key="name"/>
</field>
<field property="email" depends="required,email">
<arg key="email"/>
</field>
<field property="address" depends="required">
<arg key="address"/>
</field>
<field property="age" depends="intRange">
<arg key="age"/>
<var>
<var-name>min</var-name>
<var-value>1</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>200</var-value>
</var>
</field>
</form>
</formset>
<!-- Telugu -->
<formset language="te">
<form name="rf">
<field property="name" depends="required">
<arg key="name"/>
</field>
<field property="email" depends="required,email">
<arg key="email"/>
</field>
<field property="address" depends="required">
<arg key="address"/>
</field>
<field property="age" depends="intRange">
<arg key="age"/>
<var>
<var-name>min</var-name>
<var-value>1</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>300</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
Deployee and Test it
English:
Hindi:
Telugu
Here we have one more approach For applying i18n Through Header Parameters OF hyperlinks
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<div style="background-color: green;">
<bean:message key="cname" />
</div>
<html:form action="reg">
<pre>
<bean:message key="name" />:
<html:text property="name" />
<html:errors property="name" />
<bean:message key="email" />:
<html:text property="email" />
<html:errors property="email" />
<bean:message key="address" />: <html:textarea property="address" />
<html:errors property="address" />
<bean:message key="age" />:
<html:text property="age" />
<html:errors property="age" />
<html:submit>
<bean:message key="submit" /> </html:submit>
</pre>
</html:form>
<pre>
<html:link action="locale.do?language=te&country=IN&page=/index.jsp"
style="background-color: green;color:red;">To Telugu </html:link>
<html:link action="locale.do?language=hi&country=IN&page=/index.jsp"
style="background-color: green;color:red;">To Hindi </html:link>
<html:link action="locale.do?language=en&country=US&page=/index.jsp"
style="background-color: green;color:red;">To English </html:link>
</pre>
<struts-config>
<form-beans>
<form-bean name="i18nbean" type="org.apache.struts.action.DynaActionForm">
<form-property name="language" type="java.lang.String"/>
<form-property name="country" type="java.lang.String"/>
<form-property name="page" type="java.lang.String"/>
</form-bean>
</form-beans>
<action-mappings>
<action path="/locale" name="i18nbean"
type="org.apache.struts.actions.LocaleAction">
<forward name="sucess" path="/index.jsp"/>
</action>
<message-resources parameter="Messages"/>
</action-mappings>
</struts-config>
i.
ii.
we have to send 3 form parameters language,country,page to the
org.apache.struts.actions.LocaleAction class(built in action class)
LocaleAction It will return forward success .form the return value of
execute method
<forward path=”success” page=”/index.jsp”/>
So in that success configuration if we configure our input page in that page it
will populate the selected language properties file data
***********THANK YOU**************
Built-IN Controllers
Controller responsibility to receive request from the user and pass the request to the Model and
have to send response page based on model success or fails
In struts Architecture Request Processor will do validations by using validation classes in one hand if
validations success it will try to send that same parameters to the controller class .
Action class and Its subclasses will provide us help to write controller operations and these controller
classes strictly follows mvc principles ot will not violate MVC
There are many built in classes to handle controller operations
i.
ii.
iii.
iv.
v.
Action
DispatchAction
Lookup DispatchAction
MappingDispatchAction
Event DispatchAction
By using any one of this class we can handle controller operations.
If it is Action class
and have to override execute method in execute method we should call Model layer
classes for further operations and after receiving return value form that business methods
we should return forward success or forward fail pages to the user.
Ex:
i.
Action: If you have single button In your form you can Extend your
controller class for Action and over ride execute method (it will support
i18n incase of single button)
Find The First Hello_APP Example
ii.
DispachAction:
When we should go for dispatch action ?
If we have multiple buttons in same form or multiple forms if you want to handle them from
single Controller class (it will not support i18n features)
i.
ii.
iii.
iv.
If you extend Controller class from DA(Dispatch Action) class compulsory we should maintain
method names like button values
And method signature should be like execute method
And we should not over ride the execute method
And inside that method button related operations we have to perform
EX:
Create web project add struts1.3 capabilities
Open index.jsp
Open success.jsp page write this sample
Open error.jsp page write this sample
Open CalForm write this sample
Open CalController class write this sample
Open CalHandle class write sample
Open Messages.Properties
Open Messages_te.properties
Open struts-config.xml
In above Example we have configured some exceptions configuration also If you thought your method throws
any exception and if you want to avoid that exception stack in jsp page we can use this exception page
configurations and if you want to handle some kind of exception by your self you can go through handler
iii.
LookupDispatchAction:
To achieve i18n in your application in case of multiple buttons and multiple forms we
can go through this LookupDispatchAction. But here the problem is programmatically
we should configure mapping parameters under controller class by implementing
Public Map getkeyMethodMap(){
//prepare Map object by conf button keys with method names
}
Note: We should not over ride execute method
Ex:
Create web project add struts1.3 capabilities
Open index.jsp
Write the above example sample
Open success.jsp
Write the above example sample
Open error.jsp
Write the above example sample
Open CalController
Messsages.properties
Copy from the previous example
Messsages_te.properties
Struts-config.xml file
Copy form the previous example
iv.
EX:
MappingDispatchAction:
To configure multiple forms to A single Controller with out any static
configurations in Controller here the restriction is only one button is allowed from one
form
Note: We should not over ride execute method
Create web project add struts1.3 capabilities
Open index.jsp write sample
Open index1.jsp write sample
Open index2.jsp
Open index3.jsp
Open success.jsp
Open error.jsp
Copy CalForm,CalController,CalHandle & properties files from Dispatch Action example
Open struts-config.xml file
Deployed and Test
iv.Event DispatchAction :
If you want to configure multiple forms along with multiple buttons in a single
Controller class we can use EventDispatchAction(it will support i18n)
Note: We should not over ride execute method
Ex:
Create web project:
Open index.jsp write sample
Open index1.jsp write sample
Open success.jsp write sample
Open error.jsp write sample
Open struts-config.xml file
Deployee And Test it
Global Forwards and Global Exceptions
Open MappingDispatchAction example and
Make changes in struts-config.xml file
Based upon the Composite pattern it is built to simplify the development of user interfaces.
For complex web sites it remains
the easiest and most elegant way to work alongside any MVC technology.
EX:
MyApp
Open index.jsp write sample
Open 3r2c.jsp write sample
Open body.jsp in pages folder of webroot
Open header.html
Open footer.html
Open menu.jsp
Open Page1 folder
Change colors in header.html,footer.html,menu.html colors in <div>
<div style=”width:20%;height:200px;color:red;background-color:white;font-size:30”>
Open tiles-defs.xml
Struts-config.xml file
Deployee and Test
Make changes in tiles-defs.xml file form page1 to pages config and test it it again
Custom Request Processor
Request processor is the Application Controller class for Struts Application it will
do the actual internal operations for validation and Controller mapping and
forward page and Exception page configurations
The recommended thing is don’t override process method
And you can over ride init() and processPreProcess(), methods
Init() we can use it for 1 module initializations
processPreProcess() we can use It for any pre operations before our execute
method of controller class
Like Authentication ,Logging kind of things we can apply inside this method
(note: RP instance will create for module basis)
Ex:
Create Project add struts1.3 capabilities
Open index.jsp
Open success.jsp write code
HAI ADMIN
Open LogginActionForm write sample
Open LogginController
Open MyAuthRequestProcessor
Struts-config.xml file
PlugIn
Struts will help us to configure plugin with other frameworks by Using PlugIn interface
implementations and by configuring under struts-config.xml file
EX:
Create web project add struts1.3 ,hibernate ,spring capabilities
Open index.jsp
Open success.jsp
Open fail.jsp
FAIl
Open student bean write sample
Open StudentDAo interface write sample
Open StudentDaoImp write sample
Open StudentService interface write implementation
Open studentServiceImpl write sample
Open MySpringPluIn write sample
Open RegForm write sample
Open RegController write sample
Open spring applicationContext.xml file write sample
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="manager" />
<property name="maxActive" value="20"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="ds" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>/Student.hbm.xml</value>
</list>
</property>
</bean>
<!-- Spring Dao -->
<bean id="sdao" class="com.company.app.repository.StudentDaoImpl">
<property name="sf" ref="sessionFactory"></property>
</bean>
<!-- Service -->
<bean id="sservice" class="com.company.app.service.StudentServiceImpl">
<property name="sdao" ref="sdao"></property>
</bean></beans>
Open student.hbm.xml file write sample
Open struts-config.xml file write sample
Deploye and Test this application
****** THANK YOU********
Great Practice Hours
Download