Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
STRUTS TUTORIAL
The JSP Struts Tutorial will help new JSP developers understand the benefits of struts
What is Struts?
Struts is a popular open source framework from Apache Software Foundation to bui
Struts offers a set of tag libraries to support the faster development of the different lay
Struts is basically a Controller. It depends on other things for the model and the view
Although a dynamic web application can be developed using JSP and Servlet technology, t
" Tightly coupled classes - one change affects other classes Business logic resides in both p
multiple places to find the business rules. Also promotes duplicate business rules.
" Data sources are difficult to change as data access methods may be used in the presentat
" Logic to determine what to do next is across the application,no centralized decision.
To solve these problems,we need a mechanism that can separate the presentation layer of a
Model, View and Controller
Controller - takes the input from the user and passes it to the relevant model. The model r
Advantages of Struts
Struts offers many advantages to the application programmer while reducing the developm
Page 1 of 87
Master Of Struts 4/29/2009 12:57 PM
Form Beans
In JSP,you can use property=* with jsp:setProperty to automatically populate a JavaBean
extends this capability to Java code and adds in several useful utilities,all of which serve to
.........................................................................Bean Tags.................................................
Apache Struts provides a set of custom JSP tags (bean:write,in particular) that let you easi
................................................................................HTML tags
Apache Struts provides a set of custom JSP tags to create HTML forms that are associated
This bean/form association serves two useful purposes:
It lets you get initial form-field values from Java objects.
It lets you redisplay forms with some or all previously entered values intact.
Struts 2.0 is currently in beta phase and contains the existing Struts features plus all the fe
1. Eclipse does not come with a bundled Java Development Kit. Download and install JDK
http://java.sun.com/j2se/downloads/index.html
2. Download and install Eclipse 3.2.1 from:
http://www.eclipse.org/downloads/download.php?file=/eclipse/downloads/drops/R-3.2.1-2
pluggins which may be downloaded and installed from there respective repositories. MyEc
4. To deploy the web applications,we need a Servlet container like tomcat or JBoss. Downl
If your Eclipse version is other than 3.2.1,please download an appropriate MyEclipse plug
5. Download the source code used in this tutorial
http://www.arkaaya.com/tutorials/jsp/struts/sourcecode/eclipse-project.zip
Page 2 of 87
Master Of Struts 4/29/2009 12:57 PM
Let us consider an example - a web based user registration application. Usually every web
information. Select any database of your choice,and create a table USERS with following f
We have configured the project for struts. But wait…we are missing something. We still do
...................................Struts Configuration
Now that we have configured our project for struts,let's have a look at the configurations M
.................................................Web.xml
Page 3 of 87
Master Of Struts 4/29/2009 12:57 PM
Web.xml resides in application's WEB-INF directory and contains the essential configurati
<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>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
As we can see,there is one Servlet configured and is mapped with URL pattern *.do. What
This is the simple way how the Struts CONTROLER is plugged into the web appli
The basic reason of defining a servlet mapping for a web application is that whenever som
Page 4 of 87
Master Of Struts 4/29/2009 12:57 PM
..................................Struts-config.xml
We don't have anything special in this file configured,but as you can see,we have the basic
Let's start with our first java class. Remember we have a table "users" in the database. Let
package com.arkaaya.struts.beans;
Page 5 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 6 of 87
Master Of Struts 4/29/2009 12:57 PM
...............................................................ResourceManager
As we have already discussed,one of the main concerns of the struts framework is to separ
specified keys. To ease the manipulation of string resources where we are not using the str
package com.arkaaya.struts;
import java.util.ResourceBundle;
public class ResourceManager {
private static ResourceBundle bundle=ResourceBundle.getBundle(com.arkaaya.struts.App
public static String getString(String key){
return bundle.getString(key)
}
}
Writing the Struts Business Component Now let us write our business class that has the ab
........................................UserManager.
package com.arkaaya.struts.db;
public class UserManager {
private static UserManager mgr = null;
private UserManager()
{
}
Page 7 of 87
Master Of Struts 4/29/2009 12:57 PM
Because for one application,there can exist only a single UserManager,we have made the
Connecting to a database
The purpose of the UserManager is to provide an interface between the database and the c
package com.arkaaya.struts.db;
import java.sql.ResultSet;
import java.sql.Statement;
Page 8 of 87
Master Of Struts 4/29/2009 12:57 PM
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.arkaaya.struts.ResourceManager;
import com.arkaaya.struts.beans.User;
public class UserManager {
private static UserManager mgr = null;
private Connection con = null;
private UserManager()
{
String driverClass = ResourceManager.getString(database.driver);
String dbUrl = ResourceManager.getString(database.url);
String dbUser = ResourceManager.getString(database.user);
String dbPassword = ResourceManager.getString(database.password);
try{
Class.forName(driverClass);
con = DriverManager.getConnection(dbUrl,dbUser,dbPassword);
}catch(Exception exp){
System.err.println(Could not connect to dtabase.n exp.getMessage());
}
}
public void saveUser(User user) throws SQLException
{
if(user == null)
throw new SQLException(ResourceManager.getString(save.user.null));
Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(insert into
users(user_id,first_name,last_name,age,email) values(?,?,?,?,?));
pstmt.setString(1,user.getUserId());
pstmt.setString(2,user.getFirstName());
pstmt.setString(3,user.getLastName());
pstmt.setInt(4,user.getAge());
pstmt.setString(5,user.getEmail());
Page 9 of 87
Master Of Struts 4/29/2009 12:57 PM
pstmt.executeUpdate();
pstmt.close();
}
Page 10 of 87
Master Of Struts 4/29/2009 12:57 PM
user.setLastName(rs.getString(last_name));
user.setAge(rs.getInt(age));
user.setEmail(rs.getString(email));
list.add(user);
}
rs.close();
stmt.close();
return list;
}
private Connection getConnection() throws SQLException
{
if(con == null)
throw new SQLException(ResourceManager.getString(database.notConnected));
return con;
}
public static UserManager getInstance()
{
if(mgr == null)
{
mgr = new UserManager();
}
return mgr;
}
We have used several properties in this class. Add these properties in the ApplicationResou
Page 11 of 87
Master Of Struts 4/29/2009 12:57 PM
database.driver = sun.jdbc.odbc.JdbcOdbcDriver
database.url = jdbc:odbc:users
database.user =
database.password =
#User operations messages
save.user.null = User is null
retrieve.user.null = User is null
user.notFound = User not found
database.notConnected = Not connected to a database
Now we have all the business functions available,we are ready to move to the formal devel
The basic component of a struts based application is the Action class. Let us create the act
Adding ActionForward
<action
path=/login
type=com.arkaaya.struts.action.LoginAction
validate=false>
<forward name=success path=/manageusers.jsp />
<forward name=failure path=/index.jsp />
</action>
Note the two forwards success and the failure. The path attribute in each forward tag is the
Page 12 of 87
Master Of Struts 4/29/2009 12:57 PM
Now create index.jsp so that we have a form to submit values to this form. Add the followin
We are almost ready to run the project. But let's create a file manageusers.jsp so that if we
In our LoginAction,we retrieved the form values using the conventional methods in HttpSe
Page 13 of 87
Master Of Struts 4/29/2009 12:57 PM
public User(){
super();
}
Adding a form bean is a two step process. First of all we need to declare the form bean in
Page 14 of 87
Master Of Struts 4/29/2009 12:57 PM
The Struts framework provides a set of built-in Tag libraries that allow you to build the vie
The Tags within the Bean Library are used for creating and accessing JavaBeans and a few
The Tags within the Struts HTML Tag Library are used to create input forms for your appl
The Logic Tag Library contains tags that are helpful with iterating through collections,con
view (the index.jsp) to use the struts tag libraries to manipulate the ActionForm values,and
Note that we have created a new ActionMessage with a key "login.failed". This key must ex
login.failed = The supplied user name / password does not match
Page 15 of 87
Master Of Struts 4/29/2009 12:57 PM
As you can see,we have declared a tag library 'struts-html.tld'. This is the Html tag library
Now re-deploy the application and see yourself the difference. Did you notice the field valu
error message is displayed. This is particularly important when submitting huge forms. An
Let us write a simple action and a view that displays the user list on our manageusers.jsp.
Page 16 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 17 of 87
Master Of Struts 4/29/2009 12:57 PM
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<%boolean even = false; %>
<logic:iterate id=user name=list>
<% even = !even; %>
<tr bgcolor=<%=even?#B7D3F5:#D6E0F5 %>>
<td>
<bean:write name=user property=userId />
</td>
<td>
<bean:write name=user property=firstName />
</td>
<td>
<bean:write name=user property=lastName />
</td>
<td>
<bean:write name=user property=email />
</td>
</tr>
</logic:iterate>
<tr>
<td colspan=6 align=center>
<a href=adduser.jsp>Add New User</a>
</td>
</tr>
</table>
</logic:present>
</body>
</html>
Note that in this jsp,we have not performed any loop and still we are iterating over the list.
<action-mappings >
<action
Page 18 of 87
Master Of Struts 4/29/2009 12:57 PM
name=loginForm
path=/login
scope=request
type=com.arkaaya.struts.action.LoginAction
validate=false>
<forward name=failure path=/index.jsp />
<forward name=success path=/manageusers.do />
</action>
<action path=/manageusers type=com.arkaaya.struts.action.ManageUsersAction >
<forward name=success path=/manageusers.jsp />
</action>
</action-mappings>
On redeploying and running the application,you should be able to see a list of users on su
The variable even is used to indicate if the current row is even or odd to change the row ba
Page 19 of 87
Master Of Struts 4/29/2009 12:57 PM
type=com.arkaaya.struts.action.AddUserAction
validate=false >
<forward name=success path=/manageusers.do />
</action>
Note that we have associated the same form bean that we did when writing the LoginAction
Now it is the time to write a view component for our AddUserAction. Create a jsp page 'ad
Page 20 of 87
Master Of Struts 4/29/2009 12:57 PM
<td>Age:</td>
<td><html:text property=age /></td>
</tr>
<tr>
<td>Email:</td>
<td><html:text property=email /></td>
</tr>
<tr>
<td colspan=2 align=center><html:submit /></td>
</tr>
</table>
</html:form>
</body>
</html:html>
Run the application,login as admin/admin and click on Add New User link at the bottom of
Try to create a user with invalid values. For example an invalid email address that does no
1. Perform the validation in action class and return to failure if the validation fails.
2. Perform validation in form bean.
The first option is not feasible because one form bean may be used in many actions. So we
return ActionErrors instance with appropriate ActionError object if the validation fails,or
Page 21 of 87
Master Of Struts 4/29/2009 12:57 PM
if(getEmail().length()>0)
{{
//Yes! user entered email address. validate it
if(!getEmail().matches(^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a
errors.add(name,new ActionMessage(email.invalid));
}
}
return errors;
}
Also we need to enable the validate="true" and provide an input attribute in the action con
<action
attribute=loginForm
name=loginForm
path=/adduser
scope=request
validate=true
input=/adduser.jsp
type=com.arkaaya.struts.action.AddUserAction>
<forward name=success path=/manageusers.do />
</action>
Also we have used two error messages if the validation fails. Add these two keys in the App
After reading this tutorial you should have a good idea of how to write a Struts based web
we don't have a sophisticated IDE. After completing this tutorial,with just a few required li
What next?
Check out our related tutorials on VisualBuilder.com:
Struts Tutorial Part 2
Struts Tutorial Part 3
JSP Tutorial
Page 22 of 87
Master Of Struts 4/29/2009 12:57 PM
Hibernate Tutorial
Java Web Component Tutorial
JSP Design Tutorial
Java Tutorial
We hope you enjoyed reading this tutorial.
Be sure to come back to get updates of this tutorial.
If you would like to discuss the topics or be kept up to date then sign up to the following gr
update settings in your groups area in your profile. We will then notify you of updates.
JSP Group
Introduction
This tutorial will help you to learn many features available with the struts framework. You
The tutorial helps you to understand the Validation framework and its usefulness. You will
DispatchAction
The major component in the Struts based application is the Action class. Action class only
<action path=/dispatchActionExample
type=com.arkaaya.DispatchActionExample
parameter=method
name=inputForm
input=/index.jsp />
Note:-The above mapping will check the method parameter and call the method with the na
Add the following keys in the messageresources.properties file under WEB-INF/classes
error.unspecified= Unspecified Called.
error.add= Add Called.
error.delete= delete Called.
error.view= View Called.
Example For DispatchAction
(1) Struts-config.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
Page 23 of 87
Master Of Struts 4/29/2009 12:57 PM
<form-beans>
<form-bean name=inputForm type=com.arkaaya.InputForm />
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/dispatchActionExample
type=com.arkaaya.DispatchActionExample
parameter=method
name=inputForm
input=/index.jsp />
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
DispatchAction Example Continued...
(2) ActionForm Class
package com.arkaaya;
import org.apache.struts.action.ActionForm;
public class InputForm extends ActionForm{
}
(3) ActionClass
Note:- Now all the action classes must imherit the org.apache.struts.action.DispatchAction
org.apache.struts.action.Action Class.
package com.arkaaya;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
Page 24 of 87
Master Of Struts 4/29/2009 12:57 PM
import org.apache.struts.actions.DispatchAction;
public class DispatchActionExample extends DispatchAction{
protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpSer
HttpServletResponse response)
throws Exception {
ActionMessages message = new ActionMessages();
message.add(unspecified,new ActionMessage(error.unspecified));
saveMessages(request, message);
return mapping.getInputForward();
}
public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletReque
HttpServletResponse response) throws Exception{
Page 25 of 87
Master Of Struts 4/29/2009 12:57 PM
Output:-
The following buttons will be displayed and on clicking the buttons the text delete called ch
Introduction to DynaActionForm
In struts, every form control need to have one ActionForm class property and getter/setter
1. No ActionForm is required.
Page 26 of 87
Master Of Struts 4/29/2009 12:57 PM
Replace the property mapping with the simple xml file so that if any property is to add and
2. The mapping is to be done in the struts-config.xml file in the <form-bean> tag for all th
<form-bean name=inputForm type=org.apache.struts.action.DynaActionForm >
<form-property name=name type=java.lang.String/>
<form-property name=email type=java.lang.String />
</form-bean>
Data Types :- The types supported by DynaActionForm include:
" java.math.BigDecimal
" java.math.BigInteger
" boolean and java.lang.Boolean
" byte and java.lang.Byte
" char and java.lang.Character
" java.lang.Class
" double and java.lang.Double
" float and java.lang.Float
" int and java.lang.Integer
" long and java.lang.Long
" short and java.lang.Short
" java.lang.String
" java.sql.Date
" java.sql.Time
" java.sql.Timestamp
Example For DynaActionForm :-
(1) Struts-config.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
<form-beans>
<form-bean name=inputForm type=org.apache.struts.action.DynaActionForm >
<form-property name=name type=java.lang.String/>
<form-property name=email type=java.lang.String />
</form-bean>
</form-beans>
<!-- ========================================= Global Exceptio
Page 27 of 87
Master Of Struts 4/29/2009 12:57 PM
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/dynaActionExample
type=com.arkaaya.DynaActionFormExample
name=inputForm
input=/index.jsp />
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
DynaActionForm Example Continued...
2) ActionClass
package com.arkaaya;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.Action;
import org.apache.struts.action.DynaActionForm;
public class DynaActionFormExample extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)
throws Exception {
DynaActionForm inputForm = (DynaActionForm)form;
//Create object of ActionMesssages
ActionMessages errors = new ActionMessages();
//Check and collect errors
if(((String)inputForm.get(name)).equals()) {
errors.add(name,new ActionMessage(error.name.required));
Page 28 of 87
Master Of Struts 4/29/2009 12:57 PM
}
if(((String)inputForm.get(email)).equals()) {
errors.add(email,new ActionMessage(error.email.required));
}
//Saves the error
saveErrors(request,errors);
return mapping.getInputForward();
}
}
(3) JSP Page
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean %>
<%@ taglib uri=http://struts.apache.org/tags-html prefix=html %>
<%@ taglib uri=http://struts.apache.org/tags-logic prefix=logic %>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html>
<logic:messagesPresent>
<html:messages id=msg>
<p><strong><font color=red><bean:write name=msg /></font></strong></p>
</html:messages>
</logic:messagesPresent>
<logic:messagesPresent message=true>
<html:messages message=true id=msg>
<p><strong><bean:write name=msg /></strong></p>
</html:messages>
</logic:messagesPresent>
<html:form action=/dynaActionExample.do method=post>
<table>
<tr><td>Enter the name :- </td><td><html:text property=name/> </td></tr>
<tr><td>Enter the Email:- </td><td><html:text property=email/></td></tr>
</table>
<html:submit>Submit</html:submit>
</html:form>
</html:html>
Output:-
The following will be the output of the application.
Struts solution to Duplicate Form Submission (Token mechanism) The problem of duplicat
Page 29 of 87
Master Of Struts 4/29/2009 12:57 PM
Note:- If the Action class is changed as per the following code then it will validate against
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)
throws Exception
{
ActionMessages errors = new ActionMessages();
if (!isTokenValid(request)) {
errors.add(error.duplicaterequest, new ActionMessage(error.duplicaterequest));
}
resetToken(request);
if (!errors.isEmpty()) {
saveErrors(request, errors);
saveToken(request);
return (mapping.getInputForward());
}
return mapping.findForward(success);
}
Output
Note:- The output changes as follows :-
Introduction to Validation framework
We have seen the validate() method in ActionForm is used to validate the form properties,
similar kind of the validations for all the forms then the redundancy is increased. Also upd
very cumbersome. The Validator framework was developed by David Winterfeldt as third-p
advantages of the Validation Framework:-
It is XML based framework so it is very easy to modify the validation routines in the xml fil
Java files.
1.
2. All the validations are at the same place so the reusability of the validations are very ea
3. You can implement the validations in the Client Side as well as Server side with a little c
Page 30 of 87
Master Of Struts 4/29/2009 12:57 PM
4. The validation framework is browser independent and needs no extra effort for the differ
The Components of Validation Framework.
The basic components of the Validation Framework is as follows :-
" Validations.xml :- This is the basic class consist of all the validation rules applied for a f
Validator-rules.xml:- This is the file which contains all the validation rules which can be u
form bean data. A default file is also provided by the Struts framework which is in /org/apa
path and contains the commonly used rules,
"
Plugin mapping in Struts-Config.xml:- The mapping of the plugin is to be there in the strut
Struts controller class will configure the plugin so that it can be used in the application.
"
Simple Example For Validations :-
Note :- We are using the default validator-rules.xml for this example.
(1) Validations.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE form-validation PUBLIC -//Apache Software Foundation//DTD Commons V
1.3.0//EN http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd>
<form-validation>
<formset>
<form name=inputForm>
<field property=name depends=required>
<arg key=inputForm.name.required />
</field>
<field property=phone depends=required,mask>
<arg key=inputForm.phone.required position=0 />
<arg key=inputForm.phone.format position=1 />
<var>
<var-name>mask</var-name>
<var-value>^[0-9]*$</var-value>
</var>
</field>
<field property=email depends=required,email>
<arg key=inputForm.email.required position=0 />
<arg key=inputForm.email.format position=1 />
</field>
</form>
Page 31 of 87
Master Of Struts 4/29/2009 12:57 PM
</formset>
</form-validation>
(2) Struts-config.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC
-//Apache Software Foundation//DTD Struts Configuration 1.3//EN http://struts.apache.org
<struts-config>
<!-- ================================================ For
<form-beans>
<form-bean name=inputForm type=com.arkaaya.InputForm />
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/validate
type=com.arkaaya.ValidateAction
validate=true
name=inputForm
input=/index.jsp />
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
<!-- ===================================================
<plug-in className=org.apache.struts.validator.ValidatorPlugIn>
<set-property property=pathnames value=/org/apache/struts/validator/validator-rules.xm
/WEB-INF/validation.xml/>
</plug-in>
</struts-config>
Page 32 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 33 of 87
Master Of Struts 4/29/2009 12:57 PM
}
(4) JSP file
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean%>
<%@ taglib uri=http://struts.apache.org/tags-html prefix=html%>
<%@ taglib uri=http://struts.apache.org/tags-logic prefix=logic%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html>
<html:form action=/validate.do method=post>
<table>
<tr>
<td colspan=2>
<logic:messagesPresent>
<html:messages id=msg>
<p>
<strong><font color=red><bean:write name=msg /></font></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr>
<td colspan=2>
<logic:messagesPresent message=true>
<html:messages message=true id=msg>
<p>
<strong><bean:write name=msg /></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr><td>Enter the name</td>
<td><html:text property=name /></td></tr>
<tr><td> Enter the Phone</td>
<td> <html:text property=phone /></td></tr>
<tr><td> Enter the Email</td>
Page 34 of 87
Master Of Struts 4/29/2009 12:57 PM
Rule Description
byte Checks value contained by field can be converted to java byte type
byteLocale Checks value contained by field can be converted to java byte type using the nu
formatting convention for the current locale. creditCard Checks for the valid card number
date Checks value contained by field can be converted to java.util.Date. double Checks val
floatRange Checks value contained by field can be fitted into the primitive float range or n
integer Checks value contained by field can be converted to int primitive type. integerLoca
formatting convention for the current locale. intRange Checks value contained by field can
url Checks the given value is properly formatted URL or not. validwhen Determine the fiel
Page 35 of 87
Master Of Struts 4/29/2009 12:57 PM
validator rules. Till the time we are using the same validator-rules.xml which is the standa
struts framework.
<!--
Licensed to the Apache Software Foundation (ASF) under one or more contributor license
file distributed with this work for additional information regarding copyright ownership. T
under the Apache License, Version 2.0 (the License); you may not use this file except in co
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the L
IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. S
specific language governing permissions and limitations under the License.
-->
<!DOCTYPE form-validation PUBLIC -//Apache Software Foundation//DTD Commons V
1.3.0//EN http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd>
<!--
$Id: validator-rules.xml 481833 2006-12-03 17:32:52Z niallp $
This file contains the default Struts Validator pluggable validator definitions. It is containe
be referenced in the struts-config.xml under the plug-in element for the ValidatorPlugIn.
<plug-in className=org.apache.struts.validator.ValidatorPlugIn>
<set-property property=pathnames value=/org/apache/struts/validator/validator-rules.xm
</plug-in>
These are the default error messages associated with each validator defined in this file. Th
projects ApplicationResources.properties file or you can associate new ones by modifying
attributes in this file.
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
Page 36 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 37 of 87
Master Of Struts 4/29/2009 12:57 PM
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest/>
<validator name=minlength
classname=org.apache.struts.validator.FieldChecks
method=validateMinLength
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.minlength
jsFunction=org.apache.commons.validator.javascript.validateMinLength/>
<validator name=maxlength
classname=org.apache.struts.validator.FieldChecks
method=validateMaxLength
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.maxlength
jsFunction=org.apache.commons.validator.javascript.validateMaxLength/>
<validator name=mask
classname=org.apache.struts.validator.FieldChecks
method=validateMask
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
Page 38 of 87
Master Of Struts 4/29/2009 12:57 PM
depends=
msg=errors.invalid/>
<validator name=byte
classname=org.apache.struts.validator.FieldChecks
method=validateByte
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.byte
jsFunctionName=ByteValidations/>
<validator name=short
classname=org.apache.struts.validator.FieldChecks
method=validateShort
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.short
jsFunctionName=ShortValidations/>
<validator name=integer
classname=org.apache.struts.validator.FieldChecks
method=validateInteger
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
Page 39 of 87
Master Of Struts 4/29/2009 12:57 PM
msg=errors.integer
jsFunctionName=IntegerValidations/>
<validator name=long
classname=org.apache.struts.validator.FieldChecks
method=validateLong
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.long/>
<validator name=float
classname=org.apache.struts.validator.FieldChecks
method=validateFloat
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.float
jsFunctionName=FloatValidations/>
<validator name=double
classname=org.apache.struts.validator.FieldChecks
method=validateDouble
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.double/>
Page 40 of 87
Master Of Struts 4/29/2009 12:57 PM
<validator name=byteLocale
classname=org.apache.struts.validator.FieldChecks
method=validateByteLocale
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.byte/>
<validator name=shortLocale
classname=org.apache.struts.validator.FieldChecks
method=validateShortLocale
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.short/>
<validator name=integerLocale
classname=org.apache.struts.validator.FieldChecks
method=validateIntegerLocale
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.integer/>
<validator name=longLocale
classname=org.apache.struts.validator.FieldChecks
method=validateLongLocale
Page 41 of 87
Master Of Struts 4/29/2009 12:57 PM
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.long/>
<validator name=floatLocale
classname=org.apache.struts.validator.FieldChecks
method=validateFloatLocale
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.float/>
<validator name=doubleLocale
classname=org.apache.struts.validator.FieldChecks
method=validateDoubleLocale
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.double/>
<validator name=date
classname=org.apache.struts.validator.FieldChecks
method=validateDate
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
Page 42 of 87
Master Of Struts 4/29/2009 12:57 PM
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.date
jsFunctionName=DateValidations/>
<validator name=intRange
classname=org.apache.struts.validator.FieldChecks
method=validateIntRange
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=integer
msg=errors.range/>
<validator name=longRange
classname=org.apache.struts.validator.FieldChecks
method=validateLongRange
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=long
msg=errors.range/>
<validator name=floatRange
classname=org.apache.struts.validator.FieldChecks
method=validateFloatRange
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
Page 43 of 87
Master Of Struts 4/29/2009 12:57 PM
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=float
msg=errors.range/>
<validator name=doubleRange
classname=org.apache.struts.validator.FieldChecks
method=validateDoubleRange
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=double
msg=errors.range/>
<validator name=creditCard
classname=org.apache.struts.validator.FieldChecks
method=validateCreditCard
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.creditcard/>
<validator name=email
classname=org.apache.struts.validator.FieldChecks
method=validateEmail
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
Page 44 of 87
Master Of Struts 4/29/2009 12:57 PM
msg=errors.email/>
<validator name=url
classname=org.apache.struts.validator.FieldChecks
method=validateUrl
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest
depends=
msg=errors.url/>
<!--
This simply allows struts to include the validateUtilities into a page, it should not be used a
-->
<validator name=includeJavaScriptUtilities
classname=
method=
methodParams=
depends=
msg=
Creating custom Valdator rules
Using validation framework in our application not only provide the basic routines for the v
user flexibility to create their own specific validator rules for the application. This is the po
this saves a lot more development and validation time during the application development.
set of changes which should be performed while creating the custom validator rules for the
Steps to create the Validator rules :-
1. Create a class and add the static method for the validation.
2. Add the entry in the validator-rules.xml file.
3. Associate the rule with the form field.
4. Add the property in the MessageResources.properties for the error message.
Example
Note:- The example is merged with the Extending the Validation Rules with the inherited S
the marks field which can only take values from 1 to 100. The below is the validation class
package com.arkaaya.validator;
import java.io.Serializable;
Page 45 of 87
Master Of Struts 4/29/2009 12:57 PM
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;
/**
* This class is a custom validator which when apply to the framework checks The
* field should contain only alphabets
*
*/
public class CustomValidator implements Serializable {
public static boolean checkForRange(Object bean, ValidatorAction va, Field field, ActionM
validator,
HttpServletRequest request) {
boolean result = false;
String value = evaluateBean(bean, field);
try {
if (Integer.parseInt(value) > 0 && Integer.parseInt(value) < 100) {
result = true;
}
} catch (Exception e) {
}
if (!result) {
errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
}
return result;
}
private static String evaluateBean(Object bean, Field field) {
String value = null;
if (bean instanceof String) {
value = (String) bean;
} else {
value = ValidatorUtils.getValueAsString(bean, field.getProperty());
Page 46 of 87
Master Of Struts 4/29/2009 12:57 PM
}
return value;
}
}
Extending the Validator Rules with the inherited SubForm Classes.-2
Example Continued....
(4) ActionForm Classes
InputForm.java
package com.arkaaya;
import org.apache.struts.validator.ValidatorForm;
public class InputForm extends ValidatorForm {
String name;
String email;
String phone;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
RegistrationForm.java
package com.arkaaya;
public class RegistrationForm extends InputForm {
Page 47 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 48 of 87
Master Of Struts 4/29/2009 12:57 PM
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
return mapping.getInputForward();
}
}
(6) Output
Internationalization in struts application Few years back, the sites are only developed usin
time. This can be achieved by having the multi language text in key/value pair. And at runt
The following classes are used to implement Internationalization to any site.
Locale - The fundamental Java class that supports internationalization is Locale . Each Lo
program.
(1)MessageResources.properties
This is the default properties file. If the locale specific file is not present then struts calls th
welcome.text=default Welcome Text
(2) MessageResources_en.properties
welcome.text=English Welcome Text
(3) MessageResources_fr.properties
welcome.text=French Welcome Text
(4) MessageResources_de.properties
welcome.text=German Welcome Text
Exception Handling in Struts
Page 49 of 87
Master Of Struts 4/29/2009 12:57 PM
Struts 1.3 provides a small, but effective exception-handling framework for the application
available for the exception handling in struts.
Declarative:- In this approach the exceptions are defined in the struts-config file and in ca
occurs the control is automatically passed to the appropriate error page. The <exception>
exception in the struts-config.xml file. The following are the attributes of the <exception>
1.Key:- The key defines the key present in MessageResources.properties file to describe the
2. Type:- The class of the exception occurred.
3. Path:- The page where the control is to be followed in case exception occurred.
Handler:- The exception handler which will be called before passing the control to the file
4.With Any Action mapping:- In this approach the action class is identified which may thro
For example:-
<action path=/exception
type=com.arkaaya.ExampleAction
parameter=method
input=/index.jsp >
<exception key=error.system type=java.lang.RuntimeException path=/index.jsp />
</action>
"
Defining the Exceptions Globally for the struts-config.xml :- If the application control is to
<global-exceptions>
<exception key=error.system type=java.lang.RuntimeException path=/index.jsp />
</global-exceptions>
"
1.
Programmatic: - In this approach the exceptions are caught using normal java language tr
instead of showing the exception some meaningful messages are displayed. In this approac
also maintained by the programs. The main drawback of the approach is the developer has
the flow of the application.
2.
Page 50 of 87
Master Of Struts 4/29/2009 12:57 PM
Handlers should extend the ExceptionHandler class and override the execute() method.
The below example will demonstrate custom ExceptionHandler for the user program.
Note:- The below example will transfer the control to the index.jsp after calling the excepti
struts-config.xml we are adding the global exception for RuntimeException. You can add a
example to some actions only. The code for adding it as follows :-
<exception key=error.system type=java.lang.RuntimeException
handler=com.arkaaya.handler.CustomExceptionHandler path=/index.jsp />
Example For ExceptionHandler :-
(1) Creating the Exception Handler Class
package com.arkaaya.handler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;
public class CustomExceptionHandler extends ExceptionHandler {
public ActionForward execute(Exception exception, ExceptionConfig config, ActionMappin
formInstance,
HttpServletRequest request, HttpServletResponse response) throws ServletException {
74/
try {
// TODO CustomeCode
System.out.println(Exception Handler for the specific error);
}catch (Exception e) {
}
return (super.execute(exception, config, mapping, formInstance, request, response));
}
}
(2) Struts-config.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
Page 51 of 87
Master Of Struts 4/29/2009 12:57 PM
<struts-config>
<!-- ================================================ For
<form-beans>
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions>
<exception key=error.system type=java.lang.RuntimeException
handler=com.arkaaya.handler.CustomExceptionHandler path=/index.jsp />
</global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/exception
type=com.arkaaya.ExampleAction
input=/index.jsp />
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
Page 52 of 87
Master Of Struts 4/29/2009 12:57 PM
Note :- The below jsp will only call the Exception.do and then exception handler will pass
<%@ page language=java contentType=text/html; charset=ISO-8859-1
pageEncoding=ISO-8859-1%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<form action=exception.do>
<input type=submit value=Click>
</form>
</body>
</html>
(5) Output:-
The program will print Exception Handler for the specific error in the console window wh
CustomExceptionHandler is called before redirecting to the specific page.
Page 53 of 87
Master Of Struts 4/29/2009 12:57 PM
import org.apache.struts.config.ModuleConfig;
public class CustomPlugin implements PlugIn {
public CustomPlugin() {
super();
}
public void destroy() {
System.out.println(The plug in Destroyed);
}
public void init(ActionServlet controller, ModuleConfig config) throws ServletException {
controller.getServletContext().setAttribute(testPlugin,Testing for the object);
System.out.println(The plug in initialized);
}
}
(2) Struts-config.xml file
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
<form-beans></form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/plugin
type=com.arkaaya.TestPluginAction
input=/index.jsp >
<forward name=SUCCESS path=/index.jsp/>
</action>
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
Page 54 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 55 of 87
Master Of Struts 4/29/2009 12:57 PM
Note :-In the action mapping and action forwards, the wildcard-matched values can be acc
N is a number from 1 to 9 indicating which wildcard-matched value to substitute. The who
with the {0} token.
The action mapping attributes that will accept wildcard-matched strings are:
" attribute
" catalog
" command
" forward
" include
" input
" multipartClass
" name
" parameter
" prefix
" roles
" suffix
" type
The action forward attributes that will accept wildcard-matched strings are:
" catalog
" command
" path
The below example will demonstrate the Use of wildcard characters.
(1) Struts-config.xml
Note:- In the action mapping the parameter is passed as {1}. The jsp which invoked the ac
the name ofthe jsp in all places.
<?xml version=1.0 encoding=ISO-8859-1 ?>
Page 56 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 57 of 87
Master Of Struts 4/29/2009 12:57 PM
}
SubmitInputAction.java file
package com.arkaaya;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SubmitInputAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
System.out.println(Called SubmitInputAction file );
return mapping.getInputForward();
}
}
(3)Action Forms
InputForm.java file
package com.arkaaya;
import org.apache.struts.validator.ValidatorForm;
public class InputForm extends ValidatorForm {
String name;
String email;
String phone;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
Page 58 of 87
Master Of Struts 4/29/2009 12:57 PM
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
RegisterForm.java file
package com.arkaaya;
public class RegisterForm extends InputForm {
private String Address;
private String marks;
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
Page 59 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 60 of 87
Master Of Struts 4/29/2009 12:57 PM
</html:html>
(5) Regsiter.jsp File
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean%>
<%@ taglib uri=http://struts.apache.org/tags-html prefix=html%>
<%@ taglib uri=http://struts.apache.org/tags-logic prefix=logic%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html>
Page 61 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 62 of 87
Master Of Struts 4/29/2009 12:57 PM
<action
path=/submit
type=com.arkaaya.InputAction
name=inputForm
scope=request
validate=false
input=/index.jsp/>
</action-mappings>
<controller maxFileSize=2M />
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
(2) InputForm.java File
package com.arkaaya;
import org.apache.struts.upload.FormFile;
import org.apache.struts.validator.ValidatorForm;
public class InputForm extends ValidatorForm {
private FormFile fileName;
public FormFile getFileName() {
Page 63 of 87
Master Of Struts 4/29/2009 12:57 PM
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
public class InputAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)
throws Exception {
InputForm inputForm = (InputForm) form;
// retrieve the file representation
FormFile file = inputForm.getFileName();
// retrieve the file name
String fileName = file.getFileName();
// retrieve the content type
Generally, all the applications and systems are modularized so that the time of developmen
reduced. The struts also give the flexibility to have more than one independent modules in
struts-config files are introduced for each module. This helps developers to develop the com
effectively as different independent applications can be developed separately and then com
complete system. The struts gives a special Action class, SwitchAction , which is used for th
modules. The below example will demonstrate the modules in the Struts Applications.
The following things needs to be changed to make more than one modules in the applicatio
" All the module specific config files should be kept on the module specific directories unde
" All the jsp files for the module should be kept under the module folder.
" All the module specific files should be passed in the ActionServlet in the Web.xml file.
There are three approaches for switching from one module to another.
" You can use the org.apache.struts.actions.SwitchAction from the Extras JAR,
" you can use a <forward> (global or local) and specify the contextRelative attribute with
or you can specify the module parameter as part of any of the Struts JSP hyperlink tags (In
Rewrite, or Forward).
"
Page 64 of 87
Master Of Struts 4/29/2009 12:57 PM
Note:- The coming example will demonstrate the all three approaches for the application
Modules Example-1
Note:- In the below example we are creating the admin and register module. You can down
download link. We only show the code which is written for the modules so that you can und
switch the modules.
(1) Web.xml file Changes
<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>
<init-param>
<param-name>config/admin</param-name>
<param-value>/WEB-INF/admin/struts-admin.xml</param-value>
</init-param>
<init-param>
<param-name>config/register</param-name>
<param-value>/WEB-INF/register/struts-register.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
(2) Struts-config.xml for default Module.
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
<form-beans></form-beans>
<!-- ========================================= Global Exceptio
Modules Example-2
Page 65 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 66 of 87
Master Of Struts 4/29/2009 12:57 PM
</html:html>
(8) Output:-
Note:- On running the default module index.jsp file the following output will be displayed o
Page 67 of 87
Master Of Struts 4/29/2009 12:57 PM
input=/index.jsp/>
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
web.xml file
The mapping for the ActionServlet class is written in the web.xml file so we have to change
CustomActionServlet class.
<?xml version=1.0 encoding=UTF-8?>
<web-app version=2.4 xmlns=http://java.sun.com/xml/ns/j2ee xmlns:xsi=http://www.w3.o
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-a
Page 68 of 87
Master Of Struts 4/29/2009 12:57 PM
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>com.arkaaya.CustomActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
(3)CustomActionServlet.java file
This is the file which is the replaces the Struts Controller class. We extends the Struts Actio
behaviour and override the process method.
package com.arkaaya;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionServlet;
public class CustomActionServlet extends ActionServlet {
private static final long serialVersionUID = 1L;
public void process(HttpServletRequest request, HttpServletResponse response) throws IO
{
//TODO You can put the Code before the request handling.
System.out.println(Before Handling Request);
super.process(request,response);
//TODO You can put the Code after the request handling.
System.out.println(After Handling Request);
}
Page 69 of 87
Master Of Struts 4/29/2009 12:57 PM
}
(4)InputForm.java file
package com.arkaaya;
import org.apache.struts.validator.ValidatorForm;
public class InputForm extends ValidatorForm {
String name;
String email;
String phone;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Page 70 of 87
Master Of Struts 4/29/2009 12:57 PM
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class SubmitAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)
throws Exception {
System.out.println(Called Submit file );
return mapping.getInputForward();
}
}
(6)Index.jsp file
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean%>
<%@ taglib uri=http://struts.apache.org/tags-html prefix=html%>
<%@ taglib uri=http://struts.apache.org/tags-logic prefix=logic%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html>
<html:form action=/validate.do method=post>
<table>
<tr>
<td colspan=2>
<logic:messagesPresent>
<html:messages id=msg>
<p>
<strong><font color=red><bean:write name=msg /></font></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr>
<td colspan=2>
<logic:messagesPresent message=true>
<html:messages message=true id=msg>
Page 71 of 87
Master Of Struts 4/29/2009 12:57 PM
<p>
<strong><bean:write name=msg /></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr><td>Enter the name</td>
<td><html:text property=name /></td></tr>
<tr><td> Enter the Phone</td>
<td> <html:text property=phone /></td></tr>
<tr><td> Enter the Email</td>
<td><html:text property=email /></td></tr>
</table><html:submit>Submit </html:submit>
</html:form>
</html:html>
(7)Output
Note:- Whenever the request is submitted to the application you see two line Before Handli
Request printing on the console and the line Called Submit file is printed in between. This
code of CustomActionServlet gets called.
Page 72 of 87
Master Of Struts 4/29/2009 12:57 PM
throws Exception {
System.out.println(Called Submit file );
return mapping.getInputForward();
}
}
(6)Index.jsp file
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean%>
<%@ taglib uri=http://struts.apache.org/tags-html prefix=html%>
<%@ taglib uri=http://struts.apache.org/tags-logic prefix=logic%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html>
<html:form action=/validate.do method=post>
<table>
<tr>
<td colspan=2>
<logic:messagesPresent>
<html:messages id=msg>
<p>
<strong><font color=red><bean:write name=msg /></font></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr>
<td colspan=2>
<logic:messagesPresent message=true>
<html:messages message=true id=msg>
<p>
<strong><bean:write name=msg /></strong>
</p>
</html:messages>
</logic:messagesPresent>
</td>
</tr>
<tr><td>Enter the name</td>
Page 73 of 87
Master Of Struts 4/29/2009 12:57 PM
The previous example has shown you to customize the controller before and after any requ
provide a class named RequestProcessor which actually done all the processing for a part
whole things are done by the ActionServlet class. But with the next release the request proc
RequestProcessor class. RequestProcessor contains the processing logic that the ActionSe
each servlet request from the container. You can customize the request processing behavio
overriding the method(s) whose behavior you are interested in changing. the following met
RequestProcessor Class.
" processMultipart():- Handles the multipart request containing the images etc.
" processPath():- Identify and return the path component
" processLocale():- Automatically select a Locale for the current user, if requested.
" processContent():- Set the default content type with character encodings for all response
" processNoCache():- Set the no-cache headers for all responses, if requested.
" processPreprocess():- General-purpose preprocessing hook that can be overridden as re
" processMapping():- Select the mapping used to process the selection path for this reques
processRoles():- If this action is protected by security roles, make sure that the current use
one of them.
"
processActionForm():- Retrieve and return the ActionForm associated with this mapping,
one if necessary.
"
Page 74 of 87
Master Of Struts 4/29/2009 12:57 PM
processPopulate():- Populate the properties of the specified ActionForm instance from the
included with this request.
"
processValidate():- If this request was not cancelled, and the request's ActionMapping has
validation, call the validate method of the specified ActionForm, and forward to the input p
errors.
"
" processForward():- Process a forward requested by this mapping (if any).
" processInclude():- Process an include requested by this mapping (if any).
processActionCreate():- Return an Action instance that will be used to process the current
new one if necessary.
"
" processActionPerform():- Ask the specified Action instance to handle this request.
" processForwardConfig():- Forward or redirect to the specified destination, by the specif
Note:- The below example will demonstrate the overriding of methods in the RequestProce
override processPreprocess() method of the RequestProcessor Class. >
(1)Struts-config.xml file
Note - RequestProcessor mapping is given by the <controller> tag in the struts-config.xml
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
<form-beans>
<form-bean name=inputForm type=com.arkaaya.InputForm />
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action
path=/submit
type=com.arkaaya.SubmitAction
name=inputForm
Page 75 of 87
Master Of Struts 4/29/2009 12:57 PM
scope=request
validate=false
input=/index.jsp/>
</action-mappings>
<!-- =========================================== Controller M
<controller contentType=text/html;charset=UTF-8 locale=true debug=1 nocache=true
processorClass=com.arkaaya.CustomRequestProcessor />
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
Introduction :- A popular technique for organizing the execution of complex processing flo
Responsibility pattern. In this pattern the different "commands" are combined into a single
processing elements and the context parameter is passed along with all the parameter. All
execute method. A Boolean variable determines whether the command executes successfull
Page 76 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 77 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 78 of 87
Master Of Struts 4/29/2009 12:57 PM
exceptionCommand=servlet-exception/>
<lookup catalogName=struts name=process-action optional=false/>
<lookup catalogName=struts name=process-view optional=false/>
</chain>
<!-- ========== Action Processing chain ======================== --
<chain name=process-action>
<!--
This chain attempts to emulate (most of) the standard request processing in the standard
org.apache.struts.action.RequestProcessor class, by performing the corresponding tasks in
that are composable. The following list defines a cross reference between the processXxx m
that perform the corresponding functionality:
processMultipart Integrated into servlet and legacy classes
processPath SelectAction (which also does processMapping)
processException ExceptionCatcher / ExceptionHandler
processLocale SelectLocale
processContent SetContentType
processNoCache RequestNoCache
processPreprocess LookupCommand with optional=true. Multiple occurrences of this can
additional processing hooks at any point in the chain without modifying the standard defin
processCachedMessages RemoveCachedMessages
processMapping SelectAction (which also does processPath)
processRoles AuthorizeAction
processActionForm CreateActionForm
processPopulate PopulateActionForm
processValidate ValidateActionForm / SelectInput
processForward SelectForward
processInclude SelectInclude / PerformInclude
processActionCreate CreateAction
processActionPerform ExecuteAction
-->
<!-- Look up optional preprocess command -->
<lookup catalogName=struts name=servlet-standard-preprocess optional=true/>
<!-- Identify the Locale for this request -->
<command className=org.apache.struts.chain.commands.servlet.SelectLocale/>
<!-- Set (if needed) the URI of the original request -->
<command className=org.apache.struts.chain.commands.servlet.SetOriginalURI/>
Page 79 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 80 of 87
Master Of Struts 4/29/2009 12:57 PM
<command className=org.apache.struts.chain.commands.servlet.PerformForward/>
</chain>
<!-- ========== Servlet Exception Handler Chain =====================
<chain name=servlet-exception>
<!--
This chain is designed to be invoked (by o.a.s.c.ExceptionCatcher) if an unhandled excepti
command in a processing chain (including the one that invokes a Struts action). The standa
supports the exception mapping of Struts 1.1, but can be replaced in order to handle excep
-->
<!-- Execute the configured exception handler (if any) -->
<command className=org.apache.struts.chain.commands.servlet.ExceptionHandler/>
<!-- Follow the returned ForwardConfig (if any) -->
<command className=org.apache.struts.chain.commands.servlet.PerformForward/>
</chain>
</catalog>
Adding New Command Objects in Struts CoR Pattern
The Struts new CoR(Chain of Responsibility) structure gives us more flexibility to add our
request processing and also with less effort. All the user needs is to extend
org.apache.struts.chain.commands.ActionCommandBase class and override the execute()
The below example will demonstrate how do we insert our own command objects in the exi
changing the actual flow and the ComposeableRequestProcessor will call the file implicitly
deletion of the commands only the chain-config.xml file is changed and the Struts automati
(1) Struts-config.xml
<?xml version=1.0 encoding=ISO-8859-1 ?>
<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_3.dtd>
<struts-config>
<!-- ================================================ For
<form-beans>
<form-bean name=inputForm type=com.arkaaya.InputForm />
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
Page 81 of 87
Master Of Struts 4/29/2009 12:57 PM
SECURITY IN STRUTS
Page 82 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 83 of 87
Master Of Struts 4/29/2009 12:57 PM
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>securityapp</realm-name>
</login-config>
<security-role>
<description>Testing the Application Security</description>
<role-name>admin</role-name>
</security-role>
</web-app>
Output:-
The following screen appears when you try to run the application. It will ask for username
Page 84 of 87
Master Of Struts 4/29/2009 12:57 PM
enter visualbuilder as username and test as password then only it will display the pages of
Page 85 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 86 of 87
Master Of Struts 4/29/2009 12:57 PM
Page 87 of 87