Sei sulla pagina 1di 87

Master Of Struts 4/29/2009 12:57 PM

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

Why do we need Struts?

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

" Model - data and logic (business logic methods).

" View - output displayed to the user

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

Centralized File-Based Configuration


Rather than hard coding information into java programs,many Struts values are represent
system layout.

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.

....................................................................Form Field Validation


Apache Struts has built-in capabilities for checking that form values are in the required for
This validation can be performed on the server (in Java),or both on the server and on the c

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

..................................................................Registration Case Study

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

Column Name Data Type Constraints


USER_ID TEXT PRIMARY KEY
FIRST_NAME TEXT NONE
LAST_NAME TEXT NONE
AGE NUMBER NONE
EMAIL TEXT NONE
PASSWORD TEXT NONE
We'll use Microsoft Access database for this purpose. Use the following SQL to create tabl
CREATE TABLE USERS(
user_id text primary key,
first_name text,
last_name text,
age number,
email text,
password text
);

.......................................................Setting up Struts project in Eclipse


We are using MyEclipse as a development environment which is an eclipse plugin. Let's cr
Creating an ODBC Data source
Since Microsoft Access does not have a JDBC driver,we'll connect using the JDBC-ODBC

Create the ODBC DSN as shown below.

Configuring Application Server

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

Let's see what is in web.xml right now.

<?xml version=1.0 encoding=UTF-8?>


<web-app xmlns=http://java.sun.com/xml/ns/j2ee axmlns:xsi=http://www.w3.org/2001/XM
version=2.4 xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee qqhttp://java.sun.com/xm

<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

<?xml version=1.0 encoding=UTF-8?>


<!DOCTYPE struts-config PUBLIC -//Apache Software Foundation//DTD Struts Configur
http://struts.apache.org/dtds/struts-config_1_2.dtd>
<struts-config>
<data-sources />
<form-beans />
<global-exceptions />
<global-forwards />
<action-mappings />
<message-resources parameter=com.arkaaya.struts.ApplicationResources />
</struts-config>

We don't have anything special in this file configured,but as you can see,we have the basic

............................................Writing the User class

Let's start with our first java class. Remember we have a table "users" in the database. Let

package com.arkaaya.struts.beans;

public class User {


private String userId = ;
private String firstName = ;
private String lastName = ;
private int age = 0;
private String email = ;
private String password = ;
public User(String userId) {
super();
this.userId = userId;
}
public int getAge() {
return age;
}

Page 5 of 87
Master Of Struts 4/29/2009 12:57 PM

public void setAge(int age) {


this.age = age;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getUserId() {


return userId;
}

public void setUserId(String userId) {


this.userId = userId;
}

Page 6 of 87
Master Of Struts 4/29/2009 12:57 PM

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}
}

...............................................................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

public static UserManager getInstance()


{
if(mgr == null)
{
mgr = new UserManager();
}
return mgr;
}
}

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

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());
}
Where con is a global variable of type java.sql.Connection. Now that we have connected to
methods,UserManager

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();
}

public User getUser(String userId) throws SQLException


{
if(userId == null || userId.length() == 0)
throw new SQLException(ResourceManager.getString(retrieve.user.null));
Connection connection = getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(select * from users where user_id=&apos; userId &apos
User user = null;
if(rs.next())
{
user = new User(userId);
user.setFirstName(rs.getString(first_name));
user.setLastName(rs.getString(last_name));
user.setAge(rs.getInt(age));
user.setEmail(rs.getString(email));
}
rs.close();
stmt.close();
return user;
}

public List list() throws SQLException


{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(select * from users);
User user = null;
List list = new ArrayList();
while(rs.next())
{
user = new User(rs.getString(user_id));
user.setFirstName(rs.getString(first_name));

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;
}

public void finalize()


{
try{
con.close();
}catch(Exception exp){}
}
}

We have used several properties in this class. Add these properties in the ApplicationResou

#database connection properties

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

Creating the Action Class

The basic component of a struts based application is the Action class. Let us create the act

Adding ActionForward

The forward element in struts-config.xml describes an ActionForward that is to be made a


Local forwards can be nested within an <action> element and only available to an Action

<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

String user = request.getParameter(userId);


String password = request.getParameter(password);

Page 12 of 87
Master Of Struts 4/29/2009 12:57 PM

if(user!=null && password!=null && user.equals(admin) && password.equals(admin))


return mapping.findForward(success);
return mapping.findForward(failure);

Now create index.jsp so that we have a form to submit values to this form. Add the followin

<form action=/login.do method=post>


<table border=0>
<tr>
<td>Login:</td>
<td><input type=text name=userId /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type=text name=password /></td>
</tr>
<tr>
<td colspan=2 align=center><input type=submit value=Login/></td>
</tr>
</table>
</form>

We are almost ready to run the project. But let's create a file manageusers.jsp so that if we

Deploy the Struts Application


Now its time to test the magic of our first struts application. First step towards this is to de

Adding the Form bean

In our LoginAction,we retrieved the form values using the conventional methods in HttpSe

public class User extends ActionForm


Also we need to add a no-argument constructor to the User class to enable the struts frame

Page 13 of 87
Master Of Struts 4/29/2009 12:57 PM

public User(){
super();
}

Configuring Form Bean in struts-config.xml

Adding a form bean is a two step process. First of all we need to declare the form bean in

<form-bean name=loginForm type=com.arkaaya.struts.beans.User />


Now we will associate this form bean with the LoginAction. Update the action tag in action
like this.
<action
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.jsp />
</action>
Now update the LoginAction to retrieve form values from form bean instead of request obj
available in the request object s well. Execute method should look like this now.
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequ
request,HttpServletResponse response)
{
User userForm = (User)form;
String user = userForm.getUserId();
String password = userForm.getPassword();
if(user!=null && password!=null && user.equals(admin) && password.equals(admin))
return mapping.findForward(success);
return mapping.findForward(failure);
}
Again deploy and run the project. You should get the same behavior as you got earlier.

Using Struts Tag Libraries

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 Bean Tags

The Tags within the Bean Library are used for creating and accessing JavaBeans and a few

The HTML Tags

The Tags within the Struts HTML Tag Library are used to create input forms for your appl

The Logic Tags

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

public ActionForward execute(ActionMapping mapping,ActionForm form,


HttpServletRequest request,HttpServletResponse response) {
User userForm = (User)form;
String user = userForm.getUserId();
String password = userForm.getPassword();
if(user.equals(admin) && password.equals(admin))
return mapping.findForward(success);
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage(login.failed);
errors.add(error,error);
saveErrors(request,errors);
return mapping.findForward(failure);
}

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

And the index.jsp becomes:

<%@ page language=java pageEncoding=ISO-8859-1%>

Page 15 of 87
Master Of Struts 4/29/2009 12:57 PM

<%@taglib prefix=html uri=/WEB-INF/struts-html.tld %>


<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html>
<head>
<title>Welcome to the registration case study</title>
<!--
<link rel=stylesheet type=text/css href=styles.css>
-->
</head>
<body>
<html:errors/>
<html:form action=/login>
<table border=0>
<tr>
<td>Login:</td>
<td><html:text property=userId /></td>
</tr>
<tr>
<td>Password:</td>
<td><html:text property=password /></td>
</tr>
<tr>
<td colspan=2 align=center><html:submit value=Login/></td>
</tr>
</table>
</html:form>
</body>
</html>

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

Listing all Users - Struts Iterator Looping

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

public class ManageUsersAction extends Action {


public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) {
//Get a list of users and save to the request
try{
List list = UserManager.getInstance().list();
request.setAttribute(list,list);
}catch(SQLException sqle)
{
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage(error.generic,sqle.getMessage());
errors.add(error,error);
saveErrors(request,errors);
}
return mapping.findForward(success);
}
}
Add the following line in ApplicationResources.properties file.
error.generic = An error prevented the operation. Error detail is:<br>{0}
Add the following code in manageusers.jsp
<%@ page language=java pageEncoding=ISO-8859-1%>
<%@taglib uri=/WEB-INF/struts-html.tld prefix=html %>
<%@taglib uri=/WEB-INF/struts-logic.tld prefix=logic %>
<%@taglib uri=/WEB-INF/struts-bean.tld prefix=bean %>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html>
<head>
<title>Listing all users</title>
</head>
<body>
<center><h3>User List</h3></center>
<html:errors/>
<logic:present name=list>
<table border=0 cellspacing=0 cellpadding=0 align=center width=70% style=border-col
<tr bgcolor=#98AFCC>
<th>User ID</th>

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

Add User Action - New Struts Action Class


Now it's time to add a new user to the database. Let's write an action first that can save a u

User user = (User) form;


try{
UserManager.getInstance().saveUser(user);
}catch(SQLException sqle)
{
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage(error.generic,sqle.getMessage());
errors.add(error,error);
saveErrors(request,errors);
}
return mapping.findForward(success);
Configure this action in the struts-config.xml as given below.
<action
attribute=loginForm
name=loginForm
path=/adduser
scope=request

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

Add User View

Now it is the time to write a view component for our AddUserAction. Create a jsp page 'ad

<%@ page language=java pageEncoding=ISO-8859-1%>


<%@ taglib uri=/WEB-INF/Struts-html.tld prefix=html %>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>
<html:html lang=true>
<head>
<html:base />
<title>Add new user</title>
</head>
<body>
<center><h3>Add New User</h3></center>
<CENTER><html:errors/></CENTER>
<html:form action=/adduser method=post>
<table border=0 align=center>
<tr>
<td>User ID:</td>
<td><html:text property=userId /></td>
</tr>
<tr>
<td>First Name:</td>
<td><html:text property=firstName /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><html:text property=lastName /></td>
</tr>
<tr>

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

Validating Struts Form Bean

Try to create a user with invalid values. For example an invalid email address that does no

We have two options to do this.

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

Let's add the validation to our User class.


public ActionErrors validate(
ActionMapping mapping,HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();
if( getUserId().length()<1 ) {
errors.add(name,new ActionMessage(null.check,User ID));
}

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

null.check = {0} cannot be null or empty


email.invalid = Email address does not pass the validation rules
Now run the application and try to create a user with empty User ID or invalid email addr
Let's review what you have learnt

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{

ActionMessages message = new ActionMessages();


message.add(unspecified,new ActionMessage(error.view));
saveMessages(request, message);
return mapping.getInputForward();
}
public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletReques
HttpServletResponse response) throws Exception{
ActionMessages message = new ActionMessages();
message.add(unspecified,new ActionMessage(error.add));
saveMessages(request, message);
return mapping.getInputForward();
}
public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequ
HttpServletResponse response) throws Exception {
ActionMessages message = new ActionMessages();
message.add(unspecified,new ActionMessage(error.delete));
saveMessages(request, message);
return mapping.getInputForward();
}
}
(4) JSP Page
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean %>

Page 25 of 87
Master Of Struts 4/29/2009 12:57 PM

<%@ 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=/dispatchActionExample.do?method=add method=post>
<html:submit>Submit for add</html:submit>
</html:form>
<html:form action=/dispatchActionExample.do?method=view method=post>
<html:submit>Submit for view</html:submit>
</html:form>
<html:form action=/dispatchActionExample.do?method=delete method=post>
<html:submit>Submit for delete</html:submit>
</html:form>
<html:form action=/dispatchActionExample.do method=post>
<html:submit>Submit for unspecified</html:submit>
</html:form>
</html:html>

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

" No session associated with this request


" No transaction token saved in the session
" No transaction token included as a request parameter
" The included transaction token value does not match the transaction token in the user's s

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>

Example Continued Validation Framework.


(3) Validator Form file
package com.arkaaya;
import org.apache.struts.validator.ValidatorForm;

Page 32 of 87
Master Of Struts 4/29/2009 12:57 PM

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;
}
}
(3) Validator Action 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 ValidateAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
return mapping.getInputForward();
}

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

<td><html:text property=email /></td></tr>


</table><html:submit>Submit </html:submit>
</html:form>
</html:html>

Client Side Validation


Enabling Client Side Validation
The validation framework also gives the flexibility to use it on Client Side. The framework
browser specific JavaScript and validate the data only at the client side. Although it has so
side validations can be turn off by browser settings and also it is visible to the client. It als
reduces the network congestion as the form is not submitted with the wrong data again and
data is submitted. It is also advisable if you are using the client side validation scripts then
server side so that two way check will maintain the data integrity fully.
The following code if placed in the jsp file will generate the java script at the client side for
the validations.xml file.
<html:javascript formName=inputForm/>
To call the validation routines call the onSubmit=validateXXX(this) whereas XXX stands fo
is inputForm. So the code is as follows :-
<html:form action=/validate.do method=post onSubmit=validateInputForm(this);>
Introduction to Standard Validator-Rules.xml
The Inbuilt validation in the Validator-Rules.xml
The table will describe the validator rules available with the validator-rules.xml file provid
Community.

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

Standard validator-rules.xml file


The following is given the standard validator-rules.xml file. In the next section you will lea

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

errors.range={0} is not in the range {1} through {2}.


errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
Note: Starting in Struts 1.2.0 the default javascript definitions have been consolidated to co
can be overridden
by supplying a <javascript> element with a CDATA section, just as in struts 1.1.
-->
<form-validation>
<global>
<validator name=required
classname=org.apache.struts.validator.FieldChecks
method=validateRequired
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
msg=errors.required/>
<validator name=requiredif
classname=org.apache.struts.validator.FieldChecks
method=validateRequiredIf
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
msg=errors.required/>
<validator name=validwhen
msg=errors.required
classname=org.apache.struts.validator.validwhen.ValidWhen
method=validateValidWhen
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,

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

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) {
this.Address = address;
}
}
(5) Action Classes
ValidateAction.java
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 ValidateAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
return mapping.getInputForward();
}
}
RegisterAction.java
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;

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

ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for su

PropertyResourceBundle - One of the standard implementations of Resource Bundle allow

MessageFormat - The java.text.MessageFormat class allows you to replace portions of a m

MessageResources - The framework class org.apache.struts.util.MessageResources lets yo

The below example will show the use of Internationalization in Struts.


Note :- The example only displays the text coming from the different properties files. The p

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.

Creating Custom Exception Handlers in Struts-1


The struts not only introduced the exception handling mechanism and pass the flow to the a
it also gives the flexibility to the programmers to create their own Exception Handlers. The
org.apache.struts.action.ExceptionHandler class for creating the custom exception handler

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>

Creating Custom Exception Handlers in Struts.-2


Exception Handlers in Struts Example Continued ......
(3) Creating the Action Class
The Action class is same as we have learned just with a small change. We are throwing an
the code for the execute method is as follows:-
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
if(true){
// Throwing exception to call the Exception Handler
throw new RuntimeException(No Action);
}
return mapping.getInputForward();
}
(4) JSP Page:- index.jsp

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.

Creating Plugin for the Struts Application. -1


A Plugin is defined as the component which are easily integrated with the applications and
functionality of the system. A plug-in is any Java class that is initialized when struts applic
when application shuts down. We have already seen many plugin available for the struts li
struts framework also gives the developer flexibility to create their own plugin classes and
applications.
Example For Custom Plugins :-
(1) Creating the Plugin Class
The struts provide org.apache.struts.action.PlugIn interface. All the custom Plugin should
and override the init() and destroy() methods.
package com.arkaaya.plugin;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;

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

<!-- ======================================== Custom Plugin D


<plug-in className=com.arkaaya.plugin.CustomPlugin></plug-in>
</struts-config>

Creating Plugin for the Struts Application. -2


Example Continued....
(3) Action Class to Access the Attribute Set in the Plugin
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 TestPluginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)throws Exception {
System.out.println(servlet.getServletContext().getAttribute(testPlugin));
return mapping.findForward(SUCCESS);
}
}
(4) Output
Note:-The program will just print The plug in initialized when the server starts and Print T
call the /plugin.do action.

WildCard Character mapping for the Actions-1.


Now a days the complex application are always bigger in size. So the number of action ma
Wildcards can be used to combine similar mappings into one more generic mapping and h
config files.
Wildcard patterns can contain one or more of the following special tokens:
* Matches zero or more characters excluding the slash ('/') character.
** Matches zero or more characters including the slash ('/') character.
character The backslash character is used as an escape sequence. Thus * matches the cha
the character backslash ('').

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 ?>

<!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-bean name=RegisterForm type=com.arkaaya.RegisterForm/>
</form-beans>

Page 56 of 87
Master Of Struts 4/29/2009 12:57 PM

<!-- ========================================= Global Exceptio


<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>
<action path=/submit*
type=com.arkaaya.Submit{1}Action
name={1}Form
scope=request
validate=false
input=/{1}.jsp/>
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>

WildCard Character mapping for the Actions-2.


(2) Action Classes
SubmitRegisterAction.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;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class SubmitRegisterAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletReq
HttpServletResponse response)
throws Exception {
System.out.println(Called SubmitRegisterAction file );
return mapping.getInputForward();
}

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;
}

public String getName() {


return name;

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;
}

WildCard Character mapping for the Actions-3.


(4) Input.jsp File
<%@ taglib uri=http://struts.apache.org/tags-bean prefix=bean%>

Page 59 of 87
Master Of Struts 4/29/2009 12:57 PM

<%@ 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=/submitInput.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>
<td><html:text property=email /></td></tr>
</table><html:submit>Submit </html:submit>
</html:form>

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>

<html:form action=/submitRegister.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>

Page 61 of 87
Master Of Struts 4/29/2009 12:57 PM

<tr><td> Enter the Email</td>


<td><html:text property=email /></td></tr>
<tr><td> Enter the Address </td>
<td><html:text property=address /></td></tr>
<tr><td> Enter the Marks </td>
<td><html:text property=marks /></td></tr>
</table><html:submit>Submit </html:submit>
</html:form>
</html:html>
(6) Output
Note:- When user submits the Register form and calls the submitRegister.do action then au
the submitRegisterAction class and prints Called SubmitRegisterAction file and same as fo
submitInputAction class and prints Called SubmitInputAction file on the console.

Uploading the Files to Server Using Struts-1


Many applications gives the utility to upload the data from client applications to the server
to upload the files using the org.apache.struts.upload.FormFile class. The org.apache.stru
special class in struts which represent the property type of file. The following example will
file and place it in the upload folder by the name of temp.txt.
Example:-
(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=com.arkaaya.InputForm />
</form-beans>
<!-- ========================================= Global Exceptio
<global-exceptions></global-exceptions>
<!-- =========================================== Global Forw
<global-forwards></global-forwards>
<!-- =========================================== Action Map
<action-mappings>

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() {

Uploading the Files to Server Using Struts-2


(3) InputAction.java file
package com.arkaaya;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;

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

Introduction to Modules in Struts Application

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

(5) index.jsp file for Default Module.


<%@ 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>
This is the default Module Application<br/>
Links created for own Forward action <br/>
<a href=switchAdmin.do>Admin</a><br/>
<a href=switchRegister.do>Register</a><br/>
Links created for the SwitchAcion<br/>
<a href=switchtoAdmin.do?prefix=/admin&page=/index.jsp>Admin</a><br/>
<a href=switchtoRegister.do?prefix=/regsiter&page=/index.jsp>Register</a><br/>
Links created for the html:link tag<br/>
<html:link module=/admin page=/index.jsp>admin</html:link>
<html:link module=/register page=/index.jsp>register</html:link>
<br/>
</html:html>
(6) index.jsp file for Admin Module.
<%@ 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>
This is the Admin Module File
<a href=/switchToRegister.do?prefix=/register&page=/index.jsp>Register</a>
</html:html>
(7) index.jsp file for Register Module.
<%@ 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>
This is the Regsiter Module File
<a href=/switchToAdmin.do?prefix=/admin&page=/index.jsp>Admin</a>

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

Customizing the ActionServlet Class for the application-1.

Struts follow the Model-View-Controller pattern. ActionServlet provides the controller in t


web applications that is commonly known as Model 2. The standard version of ActionServl
following servlet initialization parameters,
config - Comma-separated list of context-relative path(s) to the XML resource(s) containin
information for the default module. (Multiple files support since Struts 1.1) [/WEB-INF/str
"
config/${module} - Comma-separated list of Context-relative path(s) to the XML resource(
configuration information for the module that will use the specified prefix (/${module}). Th
many times as required for multiple modules.
"
configFactory - The Java class name of the ModuleConfigFactory used to create the imple
ModuleConfig interface.
"
convertNull - Force simulation of the Struts 1.0 behavior when populating forms. If set to t
wrapper class types (like java.lang.Integer ) will default to null (rather than 0). (Since Stru
"
rulesets - Comma-delimited list of fully qualified classnames of additional org.apache.com
instances that should be added to the Digester that will be processing struts-config.xml file
RuleSet for the standard configuration elements is loaded.
"
validating - Should we use a validating XML parser to process the configuration file (stron
[true]
"
chainConfig - Comma-separated list of either context-relative or classloader path(s) to loa
catalog definitions from. If none specified, the default Struts catalog that is provided with S
"
The main power of struts is that you can customize the controller behaviour if needed by yo
example will demonstrate to override the default functionality of the controller and do som

Page 67 of 87
Master Of Struts 4/29/2009 12:57 PM

processing before and after the request has been processed.


(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=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
scope=request
validate=false

input=/index.jsp/>
</action-mappings>
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />

Customizing the ActionServlet Class for the application-2.

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;
}
}

Customizing the ActionServlet Class for the application-3.

(5) SubmitAction.java file


package com.arkaaya;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;

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.

Customizing the ActionServlet Class for the application-3.

(5) SubmitAction.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;
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)

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

<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.

Customizing RequestProcessor Class for the application-1.

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>

Customizing RequestProcessor Class for the application.-2

(2) CustomRequestProcessor.java file


package com.arkaaya;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.RequestProcessor;
public class CustomRequestProcessor extends RequestProcessor {
public boolean processPreprocess(HttpServletRequest request, HttpServletResponse respo
System.out .println(Called the preprocess method before processing the request);
return super.processPreprocess(request,response);
}
}
Note:- Only the above specified files are addition to the previous example i.e.Customizing
application.
(3) Output
The text Called the preprocess method before processing the request gets printed each time
Struts. This shows that it is calling the CustomRequestProcessor and not the RequestProce

ComposableRequestProcessor in Struts 1.3

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

the idea of loose coupling, a common programming practice.


From the version 1.3, the struts replaces the RequestProcessor with ComposableRequestP
Chain of Responsibility pattern (CoR) design pattern. It is configured via the following con
org.apache.struts.chain.CATALOG_NAME - Name of the Catalog in which we will look up
executed for each request. If not specified, the default value is struts.
"
org.apache.struts.chain.COMMAND_NAME - Name of the Command which we will execu
to be looked up in the specified Catalog. If not specified, the default value is servlet-standa
"
Each step of the processing is represented as a separate Command in the Chain. User can
removing and replacing the chain commands. The Command classes are following packag
1. org.apache.struts.chain.commands.
2. org.apache.struts.chain.commands.servlet packages.
The following table will listed out all the command objects of CoR.
Command Description
SelectLocale Select a locale for this request, if one hasn't already been selected, and place
request.
SetOriginalURI Store the URI of the original request in the request.
RequestNoCache If appropriate, set the following response headers: Pragma, Cache-Cont
RemoveCachedMessages
Removes any ActionMessages object stored in the session under Globals.MESSAGE_KEY
and Globals.ERROR_KEY if the messages' isAccessed method returns true. This allows
messages to be stored in the session, displayed one time, and be released.
SetContentType Set the default content type (with optional character encoding) for all resp
SelectAction Determine the ActionMapping associated with this path.
AuthorizeAction If the mapping has a role associated with it, ensure the requesting client h
role. If the client does not, raise an error and stop processing of the request.
CreateActionForm Instantiate (if necessary) the ActionForm associated with this mapping
into the appropriate scope.
PopulateActionForm Populate the ActionForm associated with this request, if any.
ValidateActionForm Perform validation (if requested) on the ActionForm associated with t
SelectInput If validation failed, select the appropriate ForwardConfig for return to the inpu
ExecuteCommand Lookup and execute a chain command if the current ActionConfig is so-
SelectForward If this mapping represents a forward, forward to the path specified by the m
SelectInclude Select the include uri (if any) for the current action mapping.
PerformInclude If selected, include the result of invoking the path in this request.

Page 77 of 87
Master Of Struts 4/29/2009 12:57 PM

CreateAction Instantiate an instance of the class specified by the current ActionMapping (i


ExecuteAction This is the point at which your Action's execute method will be called.
ExecuteForwardCommand Lookup and execute a chain command if the current ForwardC
PerformForward
Finally, the process method of the RequestProcessor takes the ActionForward returned by
your Action class, and uses it to select the next resource (if any). Most often the
ActionForward leads to the presentation page that renders the response.
The default Chain-config file supplied by the apache is as follows:-
<?xml version=1.0 ?>
<!--
$Id: chain-config.xml 481833 2006-12-03 17:32:52Z niallp $
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the License); you may not use this file except in compliance with
the License. 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 License is distributed on an AS IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
This file contains definitions of the standard Chain Of Responsibility chains that emulate S
functionality. These chains are defined in a catalog named struts so that the application ca
own purposes, without any potential for name clashes.
$Id: chain-config.xml 481833 2006-12-03 17:32:52Z niallp $
-->
<catalog name=struts>
<define name=lookup className=org.apache.commons.chain.generic.LookupCommand/>
<!-- ========== Servlet Complete Request Chain =====================
<chain name=servlet-standard>
<!-- Establish exception handling filter -->
<command className=org.apache.struts.chain.commands.ExceptionCatcher catalogNam

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

<!-- Set (if needed) no cache HTTP response headers -->


<command className=org.apache.struts.chain.commands.servlet.RequestNoCache/>
<!-- Set (if needed) the HTTP response content type -->
<command className=org.apache.struts.chain.commands.servlet.SetContentType/>
<!-- Remove messages cached in the Session -->
<command className=org.apache.struts.chain.commands.RemoveCachedMessages/>
<!-- Identify the ActionConfig for this request -->
<command className=org.apache.struts.chain.commands.servlet.SelectAction/>
<!-- Authorize the selected ActionConfig for this request -->
<command className=org.apache.struts.chain.commands.servlet.AuthorizeAction/>
<!-- Create (if needed) the ActionForm for this request -->
<command className=org.apache.struts.chain.commands.CreateActionForm/>
<!-- Populate the ActionForm for this request -->
<command className=org.apache.struts.chain.commands.servlet.PopulateActionForm/>
<!-- Validate the ActionForm for this request -->
<command className=org.apache.struts.chain.commands.servlet.ValidateActionForm/>
<!-- Select the appropriate ForwardConfig for return to input page -->
<command className=org.apache.struts.chain.commands.servlet.SelectInput/>
<!-- Lookup and execute a chain command if the current ActionConfig is so-configured. --
<command className=org.apache.struts.chain.commands.ExecuteCommand/>
<!-- Select the appropriate ForwardConfig for action mappings that only have an ActionF
<command className=org.apache.struts.chain.commands.servlet.SelectForward/>
<!-- Select the include uri (if any) for the current action mapping -->
<command className=org.apache.struts.chain.commands.SelectInclude/>
<!-- Perform the include (if needed) -->
<command className=org.apache.struts.chain.commands.servlet.PerformInclude/>
<!-- Create (if needed) the Action for this request -->
<command className=org.apache.struts.chain.commands.servlet.CreateAction/>
<!-- Execute the Action for this request -->
<command className=org.apache.struts.chain.commands.servlet.ExecuteAction/>
</chain>
<!-- ========== View Processing chain ======================== -->
<chain name=process-view>
<!-- Lookup and execute a chain command if the current ForwardConfig is so-configured.
<command className=org.apache.struts.chain.commands.ExecuteForwardCommand/>
<!-- Follow the returned ForwardConfig (if any) -->

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

<!-- =========================================== Action Map


<action-mappings>
<action
path=/submit
type=com.arkaaya.SubmitAction
name=inputForm
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=org.apache.struts.chain.ComposableRequestProcessor />
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
(2) CustomCommand.java File
Note:- The following file is created for the command object. If it returns true it means some
call the next Command in the chain and returns to the input jsp file.
package com.arkaaya.command;
import org.apache.struts.chain.commands.ActionCommandBase;
import org.apache.struts.chain.contexts.ActionContext;
public class CustomCommand extends ActionCommandBase {
@Override
public boolean execute(ActionContext ctx) throws Exception {
boolean result=true;
System.out.println(Called the logic for the Custom Command);
return false;
}
}
(3) Chain-config.xml file
Note :- The following command will be added in the chain-config.xml file anywhere in the
<!-- Execute the Custom Command for this request -->
<command className=com.arkaaya.command.CustomCommand/>

SECURITY IN STRUTS

Page 82 of 87
Master Of Struts 4/29/2009 12:57 PM

Implementation For Container Managed Implementation For Application Managed


Authentication and Authorization are specified in
web.xml.
"
It uses multiple authentication schemes, such as
Password Authentication Form-based
Authentication Client side Digital Certificates etc..
"
" Redirects are handled automatically.
User data can be provided by a variety of stores xml
file or flat files. In tomcat the Data is provided in
TOMCAT_HOME/conf/tomcat-users.xml
"
Extending RequestProcessor (in previous
versions)or AuthorizeAction (After 1.3).
"
" Cookies
" Using Servlet Filters.
" Using SSLEXT with Struts to enable HTTPS.
The following is the Example to implement the Container Specific Security in Tomcat.
(1) tomcat-user.xml File
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename=tomcat/>
<role rolename=role1/>
<role rolename=admin/>
<user username=tomcat password=tomcat roles=tomcat/>
<user username=both password=tomcat roles=tomcat,role1/>
<user username=role1 password=tomcat roles=role1/>
<user username=visualbuilder password=test roles=admin/>
</tomcat-users>
(2) Web.xml file
<?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 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

Example for the Application Managed Security-1


The same way we extends the default behaviour of the Struts application, we can validate t
some resources in the application. We have to just mention the role for the resource in the
following example will demonstrate the Application managed security. If the user enters th
submit will be called otherwise the exception page is displayed on the screen.
(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=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
scope=request validate=false
name=inputForm input=/index.jsp
roles=admin/>
</action-mappings>
<!-- =========================================== Controller M
<controller contentType=text/html;charset=UTF-8 locale=true debug=1 nocache=true
processorClass=org.apache.struts.chain.ComposableRequestProcessor />
<!-- ======================================== Message Resourc
<message-resources parameter=MessageResources />
</struts-config>
(2) chain-config.xml File

Page 85 of 87
Master Of Struts 4/29/2009 12:57 PM

Example for the Application Managed Security-2


(3) CustomCommand.java File
Note:- If any security check application is to be created in the struts 1.3 or higher then
org.apache.struts.chain.commands.AbstractAuthorizeAction is to be extended but in case o
RequestProceesor's method processRoles() is to be overridden to check the security setting
package com.arkaaya.command;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.chain.commands.AbstractAuthorizeAction;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.chain.contexts.ServletActionContext;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.util.MessageResources;
import javax.servlet.http.HttpServletRequest;
public class CustomCommand extends AbstractAuthorizeAction {
// ------------------------------------------------------- Protected Methods
protected boolean isAuthorized(ActionContext context, String[] roles, ActionConfig mappi
// Identify the HTTP request object
ServletActionContext servletActionContext = (ServletActionContext) context;
HttpServletRequest request = servletActionContext.getRequest();
// Check the current user against the list of required roles
if(request.getParameter(user) != null && request.getParameter(user).equals(admin) ){
return (true);
}
// Default to unauthorized
return (false);
}
protected String getErrorMessage(ActionContext context, ActionConfig actionConfig) {
ServletActionContext servletActionContext = (ServletActionContext) context;
// Retrieve internal message resources
ActionServlet servlet = servletActionContext.getActionServlet();
MessageResources resources = servlet.getInternal();
return resources.getMessage(notAuthorized, actionConfig.getPath());
}

Page 86 of 87
Master Of Struts 4/29/2009 12:57 PM

*********************I THOUGHT IT WILL USE full 2 U***********************


************************ *******THANK U*******************************
@R.vibhudi
@Email rajesh.vibhudi@gmail.com

Page 87 of 87

Potrebbero piacerti anche