Вы находитесь на странице: 1из 55

Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to
store, retrive and manipulate data.
The view is responsible for dispalying the results back to the user. In Struts the view
layer is implemented using JSP.
The controller handles all the request from the user and selects the appropriate
view to return. In Sruts the controller's job is done by the ActionServlet.

The following events happen when the Client browser issues an HTTP request.
 The ActionServlet receives the request.
 The struts-config.xml file contains the details regarding the Actions,
ActionForms, ActionMappings and ActionForwards.
 During the startup the ActionServelet reads the struts-config.xml file
and creates a database of configuration objects. Later while processing the request
the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks.
 Bundles all the request values into a JavaBean class which extends Struts
ActionForm class.
 Decides which action class to invoke to process the request.
 Validate the data entered by the user.
 The action class process the request with the help of the model component.
The model interacts with the database and process the request.
 After completing the request processing the Action class returns an
ActionForward to the controller.
 Based on the ActionForward the controller will invoke the appropriate view.
 The HTTP response is rendered back to the user by the view component.

In the HelloWorldForm class add the following code.


01.package com.vaannila.form;
02.  
03.import org.apache.struts.action.ActionForm;
04.  
05.public class HelloWorldForm extends ActionForm {
06.  
07.    private static final long serialVersionUID = -473562596852452021L;
08.  
09.    private String message;
10.  
11.    public String getMessage() {
12.        return message;
13.    }
14.  
15.    public void setMessage(String message) {
16.        this.message = message;
17.    }
18.}
In the same way create a new package com.vaannila.action and create a
HelloWorldAction class extending org.apache.struts.action.Action. Add the
following code to the action class and save it.
01.package com.vaannila.action;
02.  
03.import javax.servlet.http.HttpServletRequest;
04.import javax.servlet.http.HttpServletResponse;
05.  
06.import org.apache.struts.action.Action;
07.import org.apache.struts.action.ActionForm;
08.import org.apache.struts.action.ActionForward;
09.import org.apache.struts.action.ActionMapping;
10.  
11.import com.vaannila.form.HelloWorldForm;
12.  
13.public class HelloWorldAction extends Action {
14.  
15.@Override
16.public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws
Exception {
17.    HelloWorldForm hwForm = (HelloWorldForm) form;
18.    hwForm.setMessage("Hello World");
19.    return mapping.findForward("success");
20.    }
21.}
Here we typecast the ActionForm to HelloWorldForm and set the message value.
Add the following entries in the struts-config.xml file.
01.<?xml version="1.0" encoding="ISO-8859-1" ?>
02.  
03.<!DOCTYPE struts-config PUBLIC
04.          "-//Apache Software Foundation//DTD Struts Configuration
1.3//EN"
05.          "http://struts.apache.org/dtds/struts-config_1_3.dtd">
06.  
07.<struts-config>
08.  
09.    <form-beans>
10.        <form-bean name="helloWorldForm"
type="com.vaannila.form.HelloWorldForm"/>
11.    </form-beans>
12.  
13.    <global-forwards>
14.        <forward name="helloWorld" path="/helloWorld.do"/>
15.    </global-forwards>
16.  
17.    <action-mappings>
18.        <action path="/helloWorld"
type="com.vaannila.action.HelloWorldAction" name="helloWorldForm">
19.            <forward name="success" path="/helloWorld.jsp" />
20.        </action>
21.    </action-mappings>
22.  
23.</struts-config>
Now configure the deployment descriptor. Add the following configuration
information in the web.xml file.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
03.  <display-name>StrutsExample1</display-name>
04.  
05.  <servlet>
06.    <servlet-name>action</servlet-name>
07.    <servlet-class>org.apache.struts.action.ActionServlet</servlet-
class>
08.    <init-param>
09.      <param-name>config</param-name>
10.      <param-value>/WEB-INF/struts-config.xml</param-value>
11.    </init-param>
12.    <load-on-startup>2</load-on-startup>
13. </servlet>
14.  
15.  <servlet-mapping>
16.    <servlet-name>action</servlet-name>
17.    <url-pattern>*.do</url-pattern>
18.  </servlet-mapping>
19.  
20.  <welcome-file-list>
21.    <welcome-file>index.jsp</welcome-file>
22.  </welcome-file-list>
23.</web-app>
When we run the application the index.jsp page will be executed first. In the
index.jsp page we redirect the request to the helloWorld.do URI, which inturn
invokes the HelloWorldAction.
1.<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
2.<logic:redirect forward="helloWorld"/>
In the action class we return the ActionForward "success" which is mapped to the
helloWorld.jsp page. In the helloWorld.jsp page we display the "Hello World"
message.
01.<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
02.<html>
03.<head>
04.<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
05.<title>Hello World</title>
06.</head>
07.<body>
08.<bean:write name="helloWorldForm" property="message"/>
09.</body>
10.</html>
After creating all the files the directory structure of the application looks like this.
Login Application Using Action Form

In this example we will see how to create a login application using ActionForm. The
following files are required for the login application. login.jsp success.jsp failure.jsp
web.xml,struts-config.xml,LoginAction.java,LoginForm.java
,ApplicationResource.properties

web.xml
The first page that will be called in the login application is the login.jsp page. This
configuration should be done in web.xml as shown below.
1.<welcome-file-list>
2.    <welcome-file>login.jsp</welcome-file>
3.</welcome-file-list>

login.jsp
We use Struts HTML Tags to create login page. The form has one text field to get the
user name and one password field to get the password. The form also has one
submit button, which when clicked calls the login action. <html:errors /> tag is
used to display the error messages to the user.

01.      
02.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
03.<html>
04.<head>
05.<title>Login Page</title>
06.</head>
07.<body>
08.    <div style="color:red">
09.        <html:errors />
10.    </div>
11.    <html:form action="/Login" >
12.        User Name :<html:text name="LoginForm" property="userName" />
13.        Password  :<html:password name="LoginForm" property="password"
/>
14.        <html:submit value="Login" />
15.    </html:form>
16.</body>
17.</html>
The user enters the user name and password and clicks the login button. The login
action is invoked.

struts-config.xml
The validate method in the LoginForm class is called when the Form is submitted. If
any errors are found then the control is returned back to the input page where the
errors are displayed to the user. The input page is configured in the action tag of
strut-config file. <html:errors /> tag is used to display the errors in the jsp page.
01.<struts-config>
02.    <form-beans>
03.        <form-bean name="LoginForm" type="com.vaannila.LoginForm"/>
04.    </form-beans>
05.  
06.    <action-mappings>
07.        <action input="/login.jsp" name="LoginForm" path="/Login"
scope="session" type="com.vaannila.LoginAction">
08.            <forward name="success" path="/success.jsp" />
09.            <forward name="failure" path="/failure.jsp" />
10.        </action>
11.    </action-mappings>
12.</struts-config>
Here the action is "/Login" , the input page is "login.jsp" and the corresponding
action class is LoginAction.java. Now the validate method in the LoginForm class will
be invoked.

LoginForm.java
Inside the validate method, we check whether the user name and password is
entered. If not the corresponding error message is displayed to the user. The error
messages are configured in the ApplicationResource.properties file.
01.public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
02.    ActionErrors errors = new ActionErrors();
03.    if (userName == null || userName.length() < 1) {
04.        errors.add("userName", new
ActionMessage("error.userName.required"));
05.    }
06.    if (password == null || password.length() < 1) {
07.        errors.add("password", new
ActionMessage("error.password.required"));
08.    }
09.    return errors;
10.}

ApplicationResource.properties
The ApplicationResource.properties file contains the error messages. The key
"error.userName.required" is used in the validate function to add a new error.
Since the error messages are configured in a seperate properties file they can be
changed anytime without making any changes to the java files or the jsp pages.
1.error.userName.required = User Name is required.
2.error.password.required = Password is required.
If either user name or password is not entered then the corresponding error
message will be added to the ActionErrors. If any errors are found then the control is
returned back to the input jsp page, where the error messages are displayed using
the <html:errors /> tag. The validate method is used to perform the client-side
validations. Once when the input data is valid the execute method in the LoginAction
class is called.

LoginAction.java
The execute method contains the business logic of the application. Here first we
typecast the ActionForm object to LoginForm, so that we can access the form
variables using the getter and setter methods. If the user name and password is
same then we forward the user to the success page else we forward to the failure
page.
01.public class LoginAction extends org.apache.struts.action.Action {
02.  
03.    private final static String SUCCESS = "success";
04.    private final static String FAILURE = "failure";
05.  
06.    public ActionForward execute(ActionMapping mapping, ActionForm
form, HttpServletRequest request, HttpServletResponse response) throws
Exception {
07.        LoginForm loginForm = (LoginForm) form;
08.        if (loginForm.getUserName().equals(loginForm.getPassword()))
{
09.            return mapping.findForward(SUCCESS);
10.        } else {
11.            return mapping.findForward(FAILURE);
12.        }
13.    }
14.}
Lets enter the user names and password as "Eswar". Since the user name and
password is same the execute method will return an ActionForward "success". The
corresponding result associated with the name "success" will be shown to the user.
This configuration is done in struts-config.xml file.
1.<action-mappings>
2.    <action input="/login.jsp" name="LoginForm" path="/Login"
scope="session" type="com.vaannila.LoginAction">
3.        <forward name="success" path="/success.jsp" />
4.        <forward name="failure" path="/failure.jsp" />
5.    </action>
6.</action-mappings>
So according to the configuration in struts-config.xml the user will be forwarded to
success.jsp page.
If the user name and password did not match the user will be forwarded to the
failure page. Lets try entering "Joe" as the user name and "Eswar" as the password,
the following page will be displayed to the user.

You can download the source code of the Struts Login Application example by
clicking on the Download link below.

DispatchAction Class
DispatchAction provides a mechanism for grouping a set of related functions into a
single action, thus eliminating the need to create seperate actions for each functions.
In this example we will see how to group a set of user related actions like add user,
update user and delete user into a single action called UserAction.
The class UserAction extends org.apache.struts.actions.DispatchAction. This class
does not provide an implementation of the execute() method as the normal Action
class does. The DispatchAction uses the execute method to manage delegating the
request to the individual methods based on the incoming request parameter. For
example if the incoming parameter is "method=add", then the add method will be
invoked. These methods should have similar signature as the execute method.

01.public class UserAction extends DispatchAction {


02.  
03.    private final static String SUCCESS = "success";
04.  
05.    public ActionForward add(ActionMapping mapping, ActionForm form,
06.            HttpServletRequest request, HttpServletResponse response)
07.            throws Exception {
08.        UserForm userForm = (UserForm) form;
09.        userForm.setMessage("Inside add user method.");
10.        return mapping.findForward(SUCCESS);
11.    }
12.  
13.    public ActionForward update(ActionMapping mapping, ActionForm form,
14.            HttpServletRequest request, HttpServletResponse response)
15.            throws Exception {
16.        UserForm userForm = (UserForm) form;
17.        userForm.setMessage("Inside update user method.");
18.        return mapping.findForward(SUCCESS);
19.    }
20.  
21.    public ActionForward delete(ActionMapping mapping, ActionForm form,
22.            HttpServletRequest request, HttpServletResponse response)
23.            throws Exception {
24.        UserForm userForm = (UserForm) form;
25.        userForm.setMessage("Inside delete user method.");
26.        return mapping.findForward(SUCCESS);
27.    }
28.}
If you notice the signature of the add, update and delete methods are similar to the
execute method except the name. The next step is to create an action mapping for
this action handler. The request parameter name is specified using the parameter
attribute. Here the request parameter name is method.
1.<action-mappings>
2.    <action input="/index.jsp" parameter="method" name="UserForm"
path="/UserAction" scope="session" type="com.vaannila.UserAction">
3.        <forward name="success" path="/index.jsp" />
4.    </action>
5.</action-mappings>
Now lets see how to invoke a DispatchAction from jsp. We have a simple form with
three buttons to add, update and delete a user. When each button is clicked a
different method in UserAction class is invoked.
01.<html>
02.<head>
03.<script type="text/javascript">
04.function submitForm()
05.{
06.document.forms[0].action = "UserAction.do?method=add"
07.document.forms[0].submit();
08.}
09.</script>
10.</head>
11.<body>
12.<html:form action="UserAction" >
13.<table>
14.<tr>
15.    <td>
16.        <bean:write name="UserForm" property="message" />
17.    </td>
18.</tr>
19.<tr>
20.    <td>
21.        <html:submit value="Add" onclick="submitForm()" />
22.    </td>
23.</tr>
24.<tr>
25.    <td>
26.        <html:submit property="method" value="update" />
27.    </td>
28.</tr>
29.<tr>
30.    <td>
31.        <html:submit  property="method" >delete</html:submit>
32.    </td>
33.</tr>
34.</table>
35.</html:form>
36.</body>
37.</html>
Now consider the update and the delete button. The request parameter name
specified in the action handler is "method". So this should be specified as the
property name for the submit button. The name of the method to be invoked and the
value of the button should be the same. So when the button is clicked the
corresponding method in the UserAction will be called. The delete button shows an
alternate way to specify the value of the button.
Here the main constraint is the method name and the button name should be same.
So we can't have an update button like this "Update". Inorder to avoid this you can
call a javascript function on click of the button. Specify the action and submit the
form from javascript. In this way we can have a different button name and method
name. On click of the Add button the action value is set to "UserAction.do?
method=add" and the form is submitted from javascript.
On executing the sample example the following page is displayed to the user.

After clicking the add button the following page is displayed.

LookupDispatchAction Class
LookupDispatchAction provides a mechanism for grouping a set of related functions
into a single action, thus eliminating the need to create seperate actions for each
functions. In this example we will see how to group a set of user related actions like
add user, update user and delete user into a single action called UserAction.
The LookupDispatchAction class extends org.apache.struts.actions.DispatchAction.
Our class UserAction class extends LookupDispacthAction. This class does not
provide an implementation of the execute() method as the normal Action class does.
The LookupDispatchAction uses the execute method to manage delegating the
request to the individual methods based on the incoming request parameter.

01.public class UserAction extends LookupDispatchAction {


02.  
03.    private final static String SUCCESS = "success";
04.     protected Map getKeyMethodMap() {
06.        Map map = new HashMap();
07.        map.put("UserForm.add", "add");
08.        map.put("UserForm.update", "update");
09.        map.put("UserForm.delete", "delete");
10.        return map;
11.    }
12.  
13.    public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
14.        UserForm userForm = (UserForm) form;
15.        userForm.setMessage("Inside add user method.");
16.        return mapping.findForward(SUCCESS);
17.    }
18.  
19.    public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
20.        UserForm userForm = (UserForm) form;
21.        userForm.setMessage("Inside update user method.");
22.        return mapping.findForward(SUCCESS);
23.    }
24.  
25.    public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
26.        UserForm userForm = (UserForm) form;
27.        userForm.setMessage("Inside delete user method.");
28.        return mapping.findForward(SUCCESS);
29.    }
30.  
31.}
If you notice the signature of the add, update and delete methods are similar to the
execute method except the name. The UserAction class must provide an
implementation of getKeyMethodMap() method. This method maps the methods in
the action class to keys in the Struts resource bundle file. The next step is to create
an action mapping for this action handler. The request parameter name is specified
using the parameter attribute. Here the request parameter name is method.
1.<action-mappings>
2.    <action input="/index.jsp" parameter="method" name="UserForm"
path="/UserAction" scope="session" type="com.vaannila.UserAction">
3.        <forward name="success" path="/index.jsp" />
4.    </action>
5.</action-mappings>
getKeyMethodMap()
The getKeyMethodMap() method contains a HashMap. The names in the resource
bundle file are the keys for this map and the corresponding values are the method
names in the action class. For example the key value in the
ApplicationResource.properties file is "UserForm.add" and the corresponding method
name is "add" in the UserAction class. The main constraint in the DispatchAction is
the method name in the action class and the button name in the jsp page should be
the same. But here in LookupDispatchAction, we can have different names for the
buttons and the methods.
In ApplicationResource.properties file each key is mapped to a value, that value
represents the button name in the jsp page. In the getKeyMethodMap() method the
same key is mapped to a different value, this value corresponds to the method name
to be invoked in the action class.
1.ApplicationResource.properties
2.------------------------------
3.UserForm.add = Add
4.UserForm.update = Update
5.UserForm.delete = Delete
01.UserAction.java
02.---------------
03.protected Map getKeyMethodMap() {
04.    Map map = new HashMap();
05.    map.put("UserForm.add", "add");
06.    map.put("UserForm.update", "update");
07.    map.put("UserForm.delete", "delete");
08.    return map;
09.}
Here "Add", "Update" and "Delete" are the button names and "add", "update" and
"delete" are the corresponding method names. If you want to change the name of
the button at the later stage, you can easily do so by just changing the value in the
ApplicationResource.properties file without making any changes to the jsp page.
The struts-config.xml file contains the following action mapping.
1.<action-mappings>
2.    <action input="/index.jsp" name="UserForm" parameter="method"
path="/UserAction" scope="session" type="com.vaannila.UserAction">
3.        <forward name="success" path="/index.jsp" />
4.    </action>
5.</action-mappings>
The value of the parameter attribute of the action tag will be used as the request
parameter and it's value will determine which method in the action class will be
invoked. For example when the "Add" button is clicked the request parameter value
will be "method=UserForm.add" and it will invoke the corresponding "add" method
in the UserAction.
On clicking the add button the following page is displayed.

Struts HTML Tag


In this example we will see two different methods to populate a dropdown box in the
jsp page. We use HTML select tag to do this. The dropdown values are stored in two
ArrayList namely countryList and stateList. We use HTML optionsCollection tag to
display the values present in the ArrayList.
In order to use the Struts HTML Tags you need to include the following taglib
directive in the jsp page.
1.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
To use the Struts HTML Tag Library you need to add the following <taglib>
subelement to the web.xml file.
1.<taglib>
2.    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
3.    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
4.</taglib>
The jsp page contains two dropdowns one for displaying the country and the other
for displaying the state. The jsp page contains the following code.

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


02.<html>
03.<head>
04.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
05.<title>JSP Page</title>
06.</head>
07.<body>
08.<html:form action="/inputAction" >
09.<table>
10.    <tr>
11.        <td>
12.            Select Country :
13.        </td>
14.        <td>
15.            <html:select property="country" >
16.                <html:option value="0">Select Country</html:option>
17.                <html:optionsCollection name="InputForm" property="countryList"
label="countryName" value="countryId" />
18.            </html:select>
19.        </td>
20.    </tr>
21.    <tr>
22.        <td>
23.            Select State :
24.        </td>
25.        <td>
26.            <html:select property="state" >
27.                <html:option value="0">Select State</html:option>
28.                <html:optionsCollection name="InputForm" property="stateList"
label="label" value="value" />
29.            </html:select>
30.        </td>
31.    </tr>
32.    <tr>
33.    <td colspan="2" align="center">
34.        <html:submit property="method" value="save" />
35.    </td>
36.    </tr>
37.</table>
38.</html:form>
39.</body>
40.</html>
The CountryData class is used to hold the details regarding the country. The
CountryData class has countryId and countryName as attributes and the
corresponding getter and setter methods. In the jsp page we use the following code
to display the country list.
1.<html:select property="country" >
2.<html:option value="0">Select Country</html:option>
3.<html:optionsCollection name="InputForm" property="countryList"
4.label="countryName" value="countryId" />
5.</html:select>
Here we need to display the countryName as the label and the countryId as the
corresponding value. We do this using the label and the value attribute of the HTML
optionsCollection tag.
The property attribute of the HTML optionsCollection tag holds the ArrayList.
The property attribute of the HTML select tag hold the country value selected by the
user.
The input form contains the following attributes.
1.// holds the country selected by the user
2.private String country;
3.// holds the state selected by the user.
4.private String state;
5.// holds the list of countries to be displayed.
6.private ArrayList countryList;
7.// holds the list of state to be displayed.
8.private ArrayList stateList;
Here we use DispatchAction. One method is used to populate the values and the
other method is used to save the selected values. Inside the populate method we
populate the values for countryList and the stateList. The following code is used
to add a list of countries to the countryList.
1.ArrayList countryList = new ArrayList();
2.countryList.add(new CountryData("1", "USA"));
3.countryList.add(new CountryData("2", "Canada"));
4.countryList.add(new CountryData("3", "Mexico"));
We add CountryData object inside the countryList. Creating a seperate class like
this and adding it to ArrayList will be helpful if we have a few more attributes and
methods corresponding to it other than the label and value.
If we have only label and value then we can use the LabelValueBean class to add
the label and value to the ArrayList. We populate the stateList using the
LabelValueBean class. The following code is used to populate the stateList in the
action class.
1.ArrayList stateList = new ArrayList();
2.stateList.add(new LabelValueBean("New York", "1"));
3.stateList.add(new LabelValueBean("California", "2"));
4.stateList.add(new LabelValueBean("Los Angeles", "3"));
The following code is used to dispaly the state list in the jsp page.
1.<html:select property="state" >
2.<html:option value="0">Select State</html:option>
3.<html:optionsCollection name="InputForm" property="stateList"
4.label="label" value="value" />
5.</html:select>
On executing the example the following page will be dispalyed to the user.

The country and the state dropdowns are populate with the values present in the
array list.

Struts Logic Tag


In this example you will learn how to use Struts Logic Tags. In order to use the
Struts Logic Tag you need to include the following taglib directive in the jsp page.

1.<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>


To use the Struts Logic Tag Library you need to add the following <taglib>
subelement to the web.xml file.
1.<jsp-config>
2.    <taglib>
3.        <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
4.        <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
5.    </taglib>
6.</jsp-config>
In this example we will create a user.jsp page wich displays the user details
according to the conditions specified using the logic tags. The UserForm has the
following attributes and the corresponding getter and setter methods.
1.private String name;
2.private int age;
3.private float height;
4.private float weight;
5.private String favouriteFood;
6.private ArrayList hobbies;

Initially we set default values for these attributes in the UserAction.


01.public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws Exception {
02.    ArrayList hobbiesList = new ArrayList();
03.    UserForm userForm = (UserForm)form;
04.    userForm.setName("Eswar");
05.    userForm.setAge(21);
06.    userForm.setHeight(5.11f);
07.    userForm.setWeight(70f);
08.    userForm.setFavouriteFood("Fish and Chicken");
09.    hobbiesList.add("Music");
10.    hobbiesList.add("Art");
11.    hobbiesList.add("Dance");
12.    userForm.setHobbies(hobbiesList);
13.    return mapping.findForward(SUCCESS);
14.}
Based on the conditions specified using the logic tags in the jsp page, the
corresponding messages will be displayed to the user.
<logic:present /> <logic:notPresent />
The following code will dispaly "The User Name is Eswar." if the name attribute has
some value else it will display "The User is not Present."
1.<logic:present name="UserForm" property="name">
2.The User Name is Eswar.
3.</logic:present>
4.<logic:notPresent name="UserForm" property="name">
5.The User is not Present.
6.</logic:notPresent>
<logic:equal /> <logic:notEqual />
The following code will dispaly "The age is equal to 18." if the value of the age
attribute is 18 else it will dispaly "The age is not equal to 18."
1.<logic:equal name="UserForm" property="age" value="18">
2.The age is equal to 18.
3.</logic:equal>
4.<logic:notEqual name="UserForm" property="age" value="18">
5.The age is not equal to 18.
6.</logic:notEqual>
<logic:greaterEqual /> <logic:greaterThan />
The following code will dispaly "The height is greater than or equal to 5.11"
if the value of the height attribute is equal to or greater than 5.11 else it will display
"The height is greater than 5.11" if the value of the height attribute is greater
than 5.11.
1.<logic:greaterEqual name="UserForm" property="height" value="5.11">
2.The height is greater than or equal to 5.11
3.</logic:greaterEqual>
4.<logic:greaterThan name="UserForm" property="height" value="5.11">
5.The height is greater than 5.11
6.</logic:greaterThan>
<logic:lessEqual /> <logic:lessThan />
The following code will dispaly "The weight is less than or equal to 70." if the
value of the weight attribute is less than or equal to 70 else it will display "The
weight is less than 70" if the value of the weight attribute is less than 70.
1.<logic:lessEqual name="UserForm" property="weight" value="70">
2.The weight is less than or equal to 70.
3.</logic:lessEqual>
4.<logic:lessThan name="UserForm" property="weight" value="70">
5.The weight is less than 70.
6.</logic:lessThan>
<logic:match /> <logic:notMatch />
The following code will display "The user's favourite food includes Chicken" if
the value of the favouriteFood attribute contains "Chicken" else it will display "The
user's favourite food does not include Chicken".
1.<logic:match name="UserForm" property="favouriteFood" value="Chicken">
2.The user's favourite food includes Chicken.
3.</logic:match>
4.<logic:notMatch name="UserForm" property="favouriteFood" value="Chicken">
5.The user's favourite food does not includes Chicken.
6.</logic:notMatch>
<logic:iterate />
The following code is used to iterate the ArrayList and display the contents.
1.<logic:iterate name="UserForm" property="hobbies" id="data">
2.<bean:write name="data" />
3.</logic:iterate>
On executing the example the following page will be displayed to the user.
DynaActionForm Bean
DynaActionForm Beans are the extension of Form Beans that allows you to specify
the form properties inside the struts configuration file instead of creating a seperate
concreate class. It will become tedious to create a seperate form bean for each
action class. Using DynaActionForm we can easily create Form Bean in struts-
config.xml file. The struts-config.xml file entry for the DyanActionForm Bean is
shown below.

1.<form-beans>
2.    <form-bean name="LoginForm"
type="org.apache.struts.action.DynaActionForm">
3.        <form-property name="userName" type="java.lang.String" />
4.        <form-property name="password" type="java.lang.String" />
5.    </form-bean>
6.</form-beans>
The type attribute points to org.apache.struts.action.DynaActionForm and the
<form-property> tag is used to define all the form variables. The <form-property>
tag has the following three attributes.
name - The unique name of the property.
initial - The default value of the property.
type - Defines the Java type of the property. The available types are
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

Now we will see how to access the DyanActionForm in the action class.
01.public class LoginAction extends org.apache.struts.action.Action {
02.  
03.public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws Exception {
04.    DynaActionForm loginForm = (DynaActionForm) form;
05.    String userName = loginForm.get("userName").toString();
06.    String password = loginForm.get("password").toString();
07.    if(userName.equals(password))
08.    {
09.        return mapping.findForward("success");
10.    }
11.    else
12.    {
13.        return mapping.findForward("failure");
14.    }
15.}
16.}
We need to typecast the form object to DynaActionForm object in the execute
method of the action class. After that we can access the Form Bean properties. We
will consider a simple login application for our example. Here we will check the user
name and password, if they are equal then we will forward the user to the success
page, else we will forward the user to the failue page.
Now we will run the Login application. Lets enter the user name as "Eswar" and the
password as "Eswar" and click the Login button.
Struts Validator Framework
The Validator Framework in Struts consist of two XML configuration files. The first
one is the validator-rules.xml file which contains the default Struts pluggable
validator definitions. You can add new validation rules by adding an entry in this file.
The second one is the validation.xml file which contain details regarding the
validation routines that are applied to the different Form Beans. These two
configuration file should be place somewhere inside the /WEB-INF folder of the
application.
To use the validator pluggin the first step is to add it in the Struts configuration files
as shown below. The pluggin should be added after any message resource elements
in the struts configuration file as shown below.

1.<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
2.<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-
INF/validation.xml"/>
3.</plug-in>
Lets see a simple login example using the DynaValidatorForm. First we need to
create a From Bean that extends org.apache.struts.validator. DynaValidatorForm.

1.<form-beans>
2.    <form-bean name="LoginForm"
type="org.apache.struts.validator.DynaValidatorForm">
3.        <form-property name="userName" type="java.lang.String" />
4.        <form-property name="password" type="java.lang.String" />
5.    </form-bean>
6.</form-beans>
Next step is to add validations to the form fields in the validation.xml file. Our Form
name is "LoginForm" and field names are "userName" and "password".
The validation.xml file contains the following code.
01.<form-validation>
02.    <formset>
03.        <form name="LoginForm">
04.            <field property="userName" depends="required">
05.                <arg key="LoginForm.userName"/>
06.            </field>
07.            <field property="password" depends="required,minlength">
08.                <arg0 key="LoginForm.password"/>
09.                <arg1 key="${var:minlength}" name="minlength"
resource="false"/><BR>
10.                <var>
11.                <var-name>minlength</var-name>
12.                <var-value>6</var-value>
13.                </var>
14.            </field>
15.        </form>
16.    </formset>
17.</form-validation>
Each <formset> tag can contain multiple <form> tags. Specify the form name that
you want to associate with the Validation Framework as the value of the name
attribute of the form tag. Name of the form specified here should be same as the one
specified in the struts-config.xml file.
Now you can associate each properties of the form bean with one or more predefined
validation rules . The depends attribute of the field tag takes comma-delimited list of
rules to associate with each property.
The userName property is associated with the "required" rule which means that the
value cannot be empty. The error message to be displayed when a particular rule is
not satisfied is specified in the ApplicationResource.properties file.
1.LoginForm.userName = User Name
2.errors.required={0} is required.
We pass the key value as "LoginForm.userName" in the arg tag. The value for this
key will be fetched from the ApplicationResource.properties file and this value will be
used to generate the errors.required message. In our case if the userName is not
entered, the error message will be displayed as "User Name is requierd." The only
entry we need to make in the ApplicationResource.properties file is
"LoginForm.userName = User Name", the other entry is already provided by the
framework.
Inorder to associate more than one validation rule to the property we can specify a
comma-delimited list of values. The first rule in the list will be checked first and then
the next rule and so on.
Now lets see how the validation works. Click the Login button without entering any
values, the following error messages are displayed to the user.

Enter the user name as "Eswar" and password as "ab" and click the Login button, the
following error message is displayed to the user.
Highlighting Error Fileds
In this example we will see how to highlight error fields. This is done by creating a
seperate style to apply when an error has occred. This style value is set to the
errorStyleClass attribute of the corresponding Struts html tag. In our example the
login.jsp page contains the following code.

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


02.<html>
03.<head>
04.<title>
05.Highlight Error Fields
06.</title>
07.<link href="style.css" rel="stylesheet" type="text/css" />
08.</head>
09.<body>
10.<html:form action="login" >
11.    <table>
12.        <tr>
13.            <td>
14.                User Name
15.            </td>
16.            <td>
17.                <html:text property="userName" errorStyleClass="error"
18.                errorKey="org.apache.struts.action.ERROR" />
19.            </td>
20.            <td>
21.                <html:errors property="userName" />
22.            </td>
23.        </tr>
24.        <tr>
25.            <td>
26.                Password
27.            </td>
28.            <td>
29.                <html:password property="password" errorStyleClass="error"
30.                errorKey="org.apache.struts.action.ERROR" />
31.            </td>
32.            <td>
33.                <html:errors property="password" />
34.            </td>
35.        </tr>
36.        <tr>
37.            <td>
38.                 <html:submit value="Login" />
39.            </td>
40.        </tr>
41.    </table>
42.</html:form>
43.</body>
44.</html>
The style.css file has a style class "error", which sets the background to light blue
color.

1..error {
2.    background-color: #b9ecfd;
3.}
LoginForm class extends org.apache.struts.validator.ValidatorForm. All the
validations are done inside the validate method.
01.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
{
02.  
03.    ActionErrors errors = new ActionErrors();
04.    if (getUserName() == null || getUserName().length() < 1) {
05.        errors.add("userName", new ActionMessage("error.userName.required"));
06.    }
07.    if (getPassword() == null || getPassword().length() < 1) {
08.        errors.add("password", new ActionMessage("error.password.required"));
09.    } else if (getPassword().length() < 6) {
10.        errors.add("password", new ActionMessage("error.password.minlength"));
11.    }
12.    return errors;
13.  
14.}
The corresponding error messages are configured in the
ApplicationResouce.properties file.
1.error.userName.required = User Name is required.
2.error.password.required = Password is required.
3.error.password.minlength = Password can not be less than 6 characters.
Run the application. The login.jsp page will be displayed. Click the login button
without entering the User Name and the Passowrd. The following error messages will
be displayed to the user.

Enter only the user name and click the Login button, the following error message will
be displayed.

Enter a User Name and a Password less than six characters and click the Login
button, the following error message will be displayed.

You can download the source code of the highlighting error fields example by clicking
on the Download link below.

Client-Side JavaScript Validation


Struts Validator Framework provides an easy-to-use mechanism for performing
client-side validation. It's very useful to validate some fields on the client-side before
sending the data to the server for processing. By this way we can ensure that the
data send to the server is valid. Performing validations on the client-side save the
user a round trip time to the server.
For each validation routine defined in the validation-rules.xml file Struts provides
an optional JavaScript code that can run on the client-side to perform the same
validation that takes place on the server side.
Let's take a login application for our example. Our LoginForm extends
DynaValidatorForm.

1.<form-bean name="LoginForm"
type="org.apache.struts.validator.DynaValidatorForm">
2.    <form-property name="userName" type="java.lang.String" />
3.    <form-property name="password" type="java.lang.String" />
4.</form-bean>
The following validations are defined in the validation.xml file.

01.<form name="LoginForm">
02.    <field property="userName" depends="required">
03.        <arg key="LoginForm.userName"/>
04.    </field>
05.    <field property="password" depends="required,minlength">
06.        <arg0 key="LoginForm.password"/>
07.        <arg1 key="${var:minlength}" name="minlength" resource="false"/>
08.        <var>
09.            <var-name>minlength</var-name>
10.            <var-value>6</var-value>
11.        </var>
12.    </field>
13.</form>
To enable client-side validation you have to place the Struts HTML Tag Library's
javascript tag in each jsp page for which you need to preform client-side validation.
01.<html>
02.<head>
03.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
04.<title>JS Validation</title>
05.</head>
06.<body>
07.    <html:form action="/Login" onsubmit="validateLoginForm(this);">>
08.        <html:javascript formName="LoginForm" />
09.        User Name : <html:text name="LoginForm" property="userName" /> <br>
10.        Password  : <html:password name="LoginForm" property="password" />
<br>
11.        <html:submit value="Login" />
12.    </html:form>
13.</body>
14.</html>
The formName property of the javascript tag hold the name of the form specified in
the validation.xml file.
Next step is to specify the onsubmit attribute of the HTML Tag Library's form tag.
The onsubmit attribute is used to specify the javascript code that should be executed
when the form is submitted.
The name of the validate method generated by the javascipt tag is formed by
concatenating "validate" with the name of the form specified in the javascript. For
example, our form name is "LoginForm" so the generated method name will be
"validateLoginForm". If the form name is "loginForm", the generated method
name will be "validateLoginForm"
Run the application. The login.jsp page will be displayed. Click the login button
without entering the User Name and the Passowrd. The following error messages will
be displayed to the user. By using the client-side javascript validation we can display
the error messages on the alert box, instead of displaying it on the web page.

Enter only the user name and click the Login button. The following error message will
be displayed.

Enter a User Name and a Password less than six characters. The following error
message will be displayed.

Enter the User Name as "eswar" and a Password greater than six characters. The
following success page will be displayed.
Struts Date Validation Example
In this example we will see how to do date validation and email validation in struts
using validator framework. Our userForm is of type
org.apache.struts.validator.DynaValidatorForm. It contains two fields dob and
emailId. We use date rule to validate date of birth and email rule to validate email id.
The struts-config.xml file contains the following code to define the userForm.

1.<form-beans>
2.    <form-bean name="userForm"
type="org.apache.struts.validator.DynaValidatorForm">
3.        <form-property name="dob" type="java.lang.String" />
4.        <form-property name="emailId" type="java.lang.String" />
5.    </form-bean>
6.</form-beans>
Note that the dob is of type String. If any other primitive type is specified, Struts will
try to convert the incoming parameter into that primitive type. If the input is invalid,
then the validations will not run properly. Whenever the form field is subjected to
any validation use java.lang.String as its type.

The validation.xml file contains the following codes.


01.<form name="userForm">
02.    <field property="dob" depends="required,date">
03.        <arg key="userForm.dob"/>
04.        <var>
05.            <var-name>datePattern</var-name>
06.            <var-value>MM-dd-yy</var-value>
07.        </var>
08.    </field>
09.    <field property="emailId" depends="required,email">
10.        <arg key="userForm.emailId"/>
11.    </field>
12.</form>
The name attribute of the form tag in validation.xml contains the name specified in
the name attribute of the form-bean tag in struts-config.xml, in this way we
associate the validations with the form attributes. Here we need to first validate
whether the date is entered or not, for that we use the required rule.
We use the date rule to validate date. The date rule checks whether the entered date
is valid or not. The datePattern variable is used to specify the pattern used by the
date. The datePattern is implemented using java.text.SimpleDateFormat. In this
example we use the following date pattern "MM-dd-yy". In this case the dates can be
anything like this 03-21-86, 3-21-86, 03-21-1986. If you want the date to have a
strict date format then you need to use datePatternStrict. If the datePatternStrict
value is "MM-dd-yy", then it will accept only dates like 03-21-86.
Inorder to perform the email validation we use the email rule. We use the required
rule to make sure the email id is entered and then we use the email rule to vaidate
the email id.
The following messages should be configured in the ApplicationResource.properties
file. If an invalid data is entered by the user, then the following values will be used to
display the appropriate error messages.
1.userForm.dob = Date Of Birth
2.userForm.emailId = Email Id
On runing this sample date validation example the following page is displayed. The
user needs to enter a valid date and email id to register successfully.

When the user clicks the submit button without entering the date of birth and the
email id the following error messages are displayed.

When a valid date of birth is entered and the email id is not entered the following
error message is displayed to the user.

When an invalid email id is entered the following error message is displayed to the
user.
Struts 1 > Struts Custom Validation Example

Struts Custom Validation Example


In this example we will see how to do custom validation in struts. To perform custom
validation we extend the UserForm from org.apache.struts.validator.ValidatorForm.
The UserForm contains two fields one for the phone number and the other for the
mobile number. Lets take the senario where either phone number or mobile number
is mandatory. If the validation takes into account only one field at a time then Struts
Validation Framework does an excellent job. What if we need to consider more than
one form field to validate data. In this case we go for custom validation.
The UserForm class contains the following code.

01.public class UserForm extends org.apache.struts.validator.ValidatorForm {


02.  
03.    private String phoneNumber;
04.    private String mobileNumber;
05.  
06.    public String getPhoneNumber() {
07.        return phoneNumber;
08.    }
09.  
10.    public void setPhoneNumber(String phoneNumber) {
11.        this.phoneNumber = phoneNumber;
12.    }
13.  
14.    public String getMobileNumber() {
15.        return mobileNumber;
16.    }
17.  
18.    public void setMobileNumber(String mobileNumber) {
19.        this.mobileNumber = mobileNumber;
20.    }
21.  
22.    public UserForm() {
23.        super();
24.    }
25.  
26.    public ActionErrors validate(ActionMapping mapping, HttpServletRequest
request) {
27.        ActionErrors errors = super.validate(mapping, request);
28.        if ((getPhoneNumber() == null || getPhoneNumber().length() < 1) &&
29.                (getMobileNumber() == null || getMobileNumber().length() < 1)) {
30.            errors.add("phoneNumber", new
ActionMessage("error.phoneNumber.required"));
31.        }
32.        return errors;
33.    }
34.}
We will override the validate method in the UserForm to perform custom validation.
First we call the super class validate method inorder to save any errors returned by
the ValidatorForm. Then we check whether the mobile number or phone number is
present. If both are not present then we create a new ActionError and add the errors
to it. After performing all the validations we will save the errors if any and return the
ActionError object. If any errors are present the user will be forwarded to the input
page ( in our case it's the user.jsp page).
The following message should be configured in the ApplicationResource.properties
file. If either phone number or mobile number is not entered by the user then the
following error message will be displayed.
1.error.phoneNumber.required = Either Phone number of Mobile number is required.
On runing this sample custom validation example the following page is displayed.
The user needs to enter either phone number or mobile number to enter
successfully.

When the user clicks the submit button without entering both phone number and
mobile number then the following error message is displayed.
Tiles
Tiles is used to create reusable presentation components. With Tiles, we first define a
base layout with different sections after that we define which jsp page should fill in
the corresponding regions in an exteranl configuration file. The same layout can be
reused any number of times by specifying different jsp pages.
To use Tiles in the Struts application, we need to add the following <plug-in>
definition to the struts-config.xml file.
1.<plug-in className="org.apache.struts.tiles.TilesPlugin" >
2.    <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
3.    <set-property property="moduleAware" value="true" />
4.</plug-in>

There are two ways in which you can specify the Tiles definition and their attributes.
One is using JSP Tile Definition and the other way is using XML Tile Definition.
All JSP pages that uses Tiles should have the following taglib extension.
1.<%@taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Lets first design the base layout page using tiles. The base layout page is a normal
jsp page, which defines different sections. A region is defined using the
<tiles:insert> tag. The attribute value hold the name of the region.

The layout shown above can be created using the following code.
01.<html>
02.<head>
03.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
04.<title><tiles:getAsString name="title" ignore="true" /></title>
05.</head>
06.<body>
07.    <table border="1" cellpadding="2" cellspacing="2" align="center">
08.        <tr>
09.            <td height="20%" colspan="2">
10.                <tiles:insert attribute="header" ignore="true" />
11.            </td>
12.        </tr>
13.        <tr>
14.            <td width="20%" height="250">
15.                <tiles:insert attribute="menu" />
16.            </td>
17.            <td>
18.                <tiles:insert attribute="body" />
19.            </td>
20.        </tr>
21.        <tr>
22.            <td height="20%" colspan="2">
23.                <tiles:insert attribute="footer" />
24.            </td>
25.        </tr>
26.    </table>
27.</body>
28.</html>
If the ignore attribute is set to true, then that region is optional. Even if the attribute
is not specified the code will work fine.
To create our home page we need to insert title, header, menu, body and footer jsp
pages. The following code is used to create our home page.
1.<%@taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
2.<tiles:insert page="/baseLayout.jsp" flush="true">
3.    <tiles:put name="title" value="Tiles Example" />
4.    <tiles:put name="header" value="/header.jsp" />
5.    <tiles:put name="menu" value="/menu.jsp" />
6.    <tiles:put name="body" value="/body.jsp" />
7.    <tiles:put name="footer" value="/footer.jsp" />
8.</tiles:insert>
The name attribute of the put tag specifies the region in the baseLayout in which the
corresponding page specified by the value attribute should be displayed. In our
example the header region is occupied by the header.jsp page, the menu part is
occupied by the menu.jsp page, the body part by the body.jsp page and the footer
by the footer.jsp page. The only section that will be changing when the user request
a different page is the body part.
On executing the application the following home page is displayed. The table border
is set to 1 inorder to give a clear seperation between the regions.
On clicking the links in the left menu, only the body part of the page should change.
So instead of forwarding each link to a jsp page, we forward it to a Tile definition.
tiles-defs.xml file contains all the Tile definitions. A Tile definition can be added in
the following way.
1.<definition name="baseLayout" path="/baseLayout.jsp">
2.    <put name="title"  value="Tiles Example" />
3.    <put name="header" value="/header.jsp" />
4.    <put name="menu"   value="/menu.jsp" />
5.    <put name="body"   value="/body.jsp" />
6.    <put name="footer" value="/footer.jsp" />
7.</definition>
The name of the Tile definition is "baseLayout" and it contains one jsp page for each
region. Since the title region is specified using getAsString tag, we provide a String
variable instead of a jsp page. When an action is forwarded to the Tile definition
baseLayout, then the baseLayout.jsp page will be displayed with corresponding jsp
pages in the Tile definition
The powerful and useful feature of the Tile definition is the ability to extend an other
Tile definition. In our example only the tilte and the body regions are going to
change for each link in the left menu. So it is a good practice to create an new Tile
definition which extends the baseLayout, with different values for title and body
regions.
01.<definition name="friends" extends="baseLayout">
02.    <put name="title" value="Friends" />
03.    <put name="body" value="/friends.jsp" />
04.</definition>
05.  
06.<definition name="office" extends="baseLayout">
07.    <put name="title" value="The Office" />
08.    <put name="body" value="/office.jsp" />
09.</definition>
The menu.jsp contains the following code.
1.<html>
2.    <body>
3.        <a href="Link.do?method=friends" >Friends</a><br>
4.        <a href="Link.do?method=office" >The Office</a>
5.    </body>
6.</html>
On clicking each link a corresponding method in the LinkAction class is invoked.
The LinkAction class extends the DispatchAction and it contains the following
methods.
01.public class LinkAction extends DispatchAction {
02.  
03.public ActionForward friends(ActionMapping mapping, ActionForm  form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
04.    return mapping.findForward("friends");
05.}
06.  
07.public ActionForward office(ActionMapping mapping, ActionForm  form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
08.    return mapping.findForward("office");
09.}
10.}
Add the following action forward entries in the struts-config.xml file.
1.<action-mappings>
2.    <action path="/Link" parameter="method" type="com.vaannila.LinkAction">
3.        <forward name="friends" path="friends"/>
4.        <forward name="office" path="office"/>
5.    </action>
6.</action-mappings>
The path attribute hold the value of the Tile definition to forward. When the path
value is "friends" the baseLayout.jsp page is displayed with the tilte as Friends and
friends.jsp as the body.

When the path value is "office" the baseLayout.jsp page is displayed with the tilte as
The Office and office.jsp as the body.
Struts 1 > Internationalizing Struts Application

Internationalizing Struts Application


Internationalization also known as I18N is used for displaying content specific to the
locale based on their languages, currencies and formatting conventions.
Resource bundle is the file that contains the key/value pairs for the default language
of your application. The naming format for this file is
bundlename_language_country_variant.properties
For example, if you have a bundle named ApplicationResource for the English
language in the Unites States for the Windows platform, then your properties file
name would be ApplicationResource_en_US_WIN.properties.
Lets take a senario in which the user can see the same page in four different
languages like English, French, German and Italian. The jsp page gets displayed
according to the language selected by the user.
Our default resource bundle is ApplicationResource.properties file. To link the
resouce bundle with the application the following tag should be added in the struts-
config.xml file.

1.<message-resources parameter="com/vaannila/ApplicationResource"/>
The next step is to create ApplicationResource.properties file specific to each
language.
French - ApplicationResource_fr.properties
1.label.welcome = J'aime Struts
Italian - ApplicationResource_it.properties
1.label.welcome = ti amo Struts
German - ApplicationResource_de.properties
1.label.welcome = Ich liebe Struts
There are two ways in which you can internationalize struts application. One is by
setting the org.apache.struts.action.LOCALE to the corresponding language and the
other way is to set the language preference in the browser.
In this example we will see how to internationalize Struts application by setting
different values to org.apache.struts.action.LOCALE variable.
Based on the language selected by the user the corresponding method in the
LocaleAction is called. LocaleAction class extends DispatchAction.
01.public class LocaleAction extends DispatchAction {
02.  
03.    private final static String SUCCESS = "success";
04.  
05.    public ActionForward english(ActionMapping mapping, ActionForm  form,
06.            HttpServletRequest request, HttpServletResponse response)
07.            throws Exception {
08.        HttpSession session = request.getSession();
09.        session.setAttribute("org.apache.struts.action.LOCALE", Locale.ENGLISH);
10.        return mapping.findForward(SUCCESS);
11.    }
12.  
13.    public ActionForward french(ActionMapping mapping, ActionForm  form,
14.            HttpServletRequest request, HttpServletResponse response)
15.            throws Exception {
16.        HttpSession session = request.getSession();
17.        session.setAttribute("org.apache.struts.action.LOCALE", Locale.FRENCH);
18.        return mapping.findForward(SUCCESS);
19.    }
20.  
21.    public ActionForward german(ActionMapping mapping, ActionForm  form,
22.            HttpServletRequest request, HttpServletResponse response)
23.            throws Exception {
24.        HttpSession session = request.getSession();
25.        session.setAttribute("org.apache.struts.action.LOCALE", Locale.GERMAN);
26.        return mapping.findForward(SUCCESS);
27.    }
28.  
29.    public ActionForward italian(ActionMapping mapping, ActionForm  form,
30.            HttpServletRequest request, HttpServletResponse response)
31.            throws Exception {
32.        HttpSession session = request.getSession();
33.        session.setAttribute("org.apache.struts.action.LOCALE", Locale.ITALIAN);
34.        return mapping.findForward(SUCCESS);
35.    }
36.}
Based on the value set in the org.apache.struts.action.LOCALE variable the
corresponding ApplicationResource.properties file will be used for displaying data.
Run the application. The following page will be dispalyed to the user.
On selecting the french language the following page will be displayed.

On selecting the german language the following page will be displayed.

On selecting the italian language the following page will be displayed.

Internationalizing Struts Application


Internationalization also known as I18N is used for displaying content specific to the
locale based on their languages, currencies and formatting conventions.
Resource bundle is the file that contains the key/value pairs for the default language
of your application. The naming format for this file is
bundlename_language_country_variant.properties
For example, if you have a bundle named ApplicationResource for the English
language in the Unites States for the Windows platform, then your properties file
name would be ApplicationResource_en_US_WIN.properties.
Lets take a senario in which the user can see the same page in four different
languages like English, French, German and Italian. The jsp page gets displayed
according to the language selected by the user.
Our default resource bundle is ApplicationResource.properties file. To link the
resouce bundle with the application the following tag should be added in the struts-
config.xml file.

1.<message-resources parameter="com/vaannila/ApplicationResource"/>
The ApplicationResource.properties file contains the following key/value pairs.
1.label.user = User
2.label.password = Password
3.label.button = Login
The next step is to create ApplicationResource.properties file specific to the french
language.
French - ApplicationResource_fr.properties
1.label.user = Usager
2.label.password = Mot de passe
3.label.button = Entrer
In this example we will see how to internationalize Struts application according to the
language selected in the browser.
Here we don't specify any language specific values in the jsp page, instead we
specify them in the ApplicationResource.properties file and display them using
<bean:message> tag. The index.jsp page contains the following code.
01.<html>
02.<head>
03.<title>
04.Strus - I18N
05.</title>
06.</head>
07.<body>
08.<table>
09.    <tr>
10.        <td>
11.            <bean:message key="label.user" />
12.        </td>
13.        <td>
14.            <input type="text" name="user" />
15.        </td>
16.    </tr>
17.    <tr>
18.        <td>
19.            <bean:message key="label.password" />
20.        </td>
21.        <td>
22.            <input type="password" name="pass" />
23.        </td>
24.    </tr>
25.    <tr>
26.        <td colspan="2" align="center">
27.            <input type="button" value='<bean:message key="label.button" />' />
28.        </td>
29.    </tr>
30.</table>
31.</body>
32.</html>
According to the language selected in the browser, the corresponding properties file
will be used to fetch the key values. If the language is "en" then the key values will
be taken from the ApplicationResource.properties file. If the language is "fr" then the
key values will be taken from the ApplicationResource_fr.properties file
By default the language selectd in the browser is English ("en"), so when we run the
example the following page is displayed.

Lets change the Language to French ("fr"). Go to Internet Explorer -> Tools ->
Internet Options -> Click the Languages button -> Add the French language -> Move
the French language to the first position.

Refresh the screen. Now all the user messages will be displayed in the French
language.
You can download the source code of the Struts Internationalization example by
clicking on the

Export JSP Page to Excel


01.<%@page contentType="text/html" pageEncoding="UTF-8"%>
02.<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
03.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
04.<html>
05.<head>
06.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
07.<title>User Details</title>
08.</head>
09.<body>
10.<table cellpadding="3" cellspacing="3" border="1">
11.    <tr>
12.        <th>
13.            User Name
14.        </th>
15.        <th>
16.            Email Id
17.        </th>
18.        <th>
19.            Location
20.        </th>
21.    </tr>
22.    <logic:iterate id="data" name="ExcelForm" property="userList">
23.        <tr>
24.            <td>
25.                <bean:write name="data" property="userName" />
26.            </td>
27.            <td>
28.                <bean:write name="data" property="emailId" />
29.            </td>
30.            <td>
31.                <bean:write name="data" property="location" />
32.            </td>
33.        </tr>
34.    </logic:iterate>
35.</table>
36.<a href="exportUser.jsp" >Excel</a>
37.</body>
38.</html>
In the user.jsp page we iterate the userList using the <logic:iterate> tag. The id
attribute of the <logic:iterate> tag holds an instance of the data present in the
userList. userList contains a list of UserData. So the id attribute holds an instance of
the UserData. Using the <bean:write> tag we display the data present in the
UserData.
The exportUser.jsp page contains the following contents.
01.<%@page contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>
02.  
03.<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
04.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
05.<html>
06.<head>
07.<title>User Details</title>
08.</head>
09.<body>
10.<table cellpadding="3" cellspacing="3" border="1">
11.    <tr>
12.        <th>
13.            User Name
14.        </th>
15.        <th>
16.            Email Id
17.        </th>
18.        <th>
19.            Location
20.        </th>
21.    </tr>
22.    <logic:iterate id="data" name="ExcelForm" property="userList">
23.        <tr>
24.            <td>
25.                <bean:write name="data" property="userName" />
26.            </td>
27.            <td>
28.                <bean:write name="data" property="emailId" />
29.            </td>
30.            <td>
31.                <bean:write name="data" property="location" />
32.            </td>
33.        </tr>
34.    </logic:iterate>
35.</table>
36.</body>
37.</html>
The user.jsp page contains the following user details.

On clicking the Excel link in the user.jsp page. The userDetails.jsp page will be
displayed in the Excel fromat.

1.<bean:write name="data" property="userName" />


The above mentioned tag calls the getUserName() method of the UserData class and
displays the user name. A link is provided to export the exportUser.jsp page to excel.
The exportUser.jsp page contains similar data like the user.jsp page except the
contentType attribute of the page directive, which is set to application/vnd.ms-excel.

You can download the source code of the export Jsp to Excel example by clicking on
the Download link below.

Struts 1 > Export to Excel, PDF, CSV and XML using Display tag

Export to Excel, PDF, CSV and XML using Display tag


Using display tag library, we can export the data grid as excel, pdf, csv and xml. In
the following example we will see how to dispaly data using display tag and to export
as excel, pdf, csv and xml.
The following jar files should be placed in the WEB-INF/lib directory
antlr ,commons-beanutils ,commons-beanutils-1.7.0 commons-collections-3.1
commons-digester commons-fileupload-1.0 commons-lang-2.3 commons-
logging commons-validator displaytag-1.2 displaytag-export-poi-1.2 displaytag-
portlet-1.2 itext-1.3
jakarta-oro
log4j-1.2.13
struts

itext-1.3.jar file is required incase of exporting to pdf. displaytag-export-poi-1.2.jar


is requried to export the file as csv, xml and excel.The following taglib directive
should be placed in each JSP page that uses the display tag.

1.<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>


In this example we will display a list of actor's details like name, email Id and the TV
show in which they performed. In this example we have a ActorData class which
store the actor's details like name, email id and the tv show. The ActorData class has
a loadData() method which returns an ArrayList of all the actor details.
The following attributes and methods are present in the ActorData class.
01.public class ActorData
02.{
03.  private String tvShow;
04.  private String userName;
05.  private String emailId;
06.  public ActorData()
07.  {
08.  
09.  }
10.  
11.  public ActorData(String tvShow, String userName, String emailId)
12.  {
13.      this.tvShow = tvShow;
14.      this.userName = userName;
15.      this.emailId = emailId;
16.  }
17.  public ArrayList loadData()
18.  {
19.      ArrayList userList = new ArrayList();
20.      userList.add(new ActorData("The Office","Michael Scott",
21.            "michael.scott@dundermifflin.com"));
22.      userList.add(new ActorData("The Office","Dwight Schrute",
23.            "dwight.schrute@dundermifflin.com"));
24.      userList.add(new ActorData("The Office","Jim Halpert",
25.            "jim.halpert@dundermifflin.com"));
26.      userList.add(new ActorData("The Office","Pam Beesly",
27.            "pam.beesly@dundermifflin.com"));
28.      userList.add(new ActorData("The Office","Andy Bernad",
29.            "andy.bernad@dundermifflin.com"));
30.      userList.add(new ActorData("The Office","Angela Martin",
31.            "angela.martin@dundermifflin.com"));
32.      userList.add(new ActorData("Friends","Rachel Green",
33.            "rachel.green@friends.com"));
34.      userList.add(new ActorData("Friends","Monica Geller",
35.            "monica.geller@friends.com"));
36.      userList.add(new ActorData("Friends","Phoebe Buffay",
37.            "phoebe.buffay@friends.com"));
38.      userList.add(new ActorData("Friends","Joey Tribbiani",
39.            "joey.tribbiani@friends.com"));
40.      userList.add(new ActorData("Friends","Chandler Bing",
41.            "chandler.bing@friends.com"));
42.      userList.add(new ActorData("Friends","Ross Geller",
43.            "ross.geller@friends.com"));
44.      return userList;
45.  }
46.  public String getTvShow() {
47.    return tvShow;
48.  }
49.  public String getUserName() {
50.    return userName;
51.  }
52.  public String getEmailId() {
53.    return emailId;
54.  }
55.  
56.}
In the execute() method of the UserAction class, the loadData() method of ActorData
class is called. This method will return an ArrayList of actors, that ArrayList is stored
in the actorList attribute of the UserForm class.
1.public ActionForward execute(ActionMapping mapping, ActionForm
form,HttpServletRequest request, HttpServletResponse response) throws Exception {
2.    UserForm userForm = (UserForm) form;
3.    ActorData actorData = new ActorData();
4.    userForm.setActorList(actorData.loadData());
5.    return mapping.findForward(SUCCESS);
6.}
Now we will display all the actor data present in the actorList in the jsp page using
dispalytag.
1.<display:table id="data" name="sessionScope.UserForm.actorList"
requestURI="/userAction.do" pagesize="10" >
2.<display:column property="tvShow" title="TV Show" sortable="true"
media="html" group="1" />
3.<display:column property="userName" title="User Name" sortable="true"/>
4.<display:column property="emailId" title="Email Id" sortable="true"/>
5.</display:table>
The export attribute of the table tag should be set to true, inorder to export the data
grid. After setting the value the data grid can be exported to excel, csv and xml. If
you want to export to pdf then the "export.pdf" property to true.
1.<display:setProperty name="export.pdf" value="true" />
By default the name of the export file will be the name of the jsp page. You can
change the name of the pdf file by setting the "export.pdf.filename" property
value to the desired file name. In the similar way you can change the name of the
excel file by setting "export.excel.filename" property to a desired file name.
1.<display:setProperty name="export.pdf.filename" value="ActorDetails.pdf"/>
2.<display:setProperty name="export.excel.filename" value="ActorDetails.xls"/>
The name attribute of the table tag hold the name of the list in the form. The id
value specifies an instance name for the ArrayList. The pagesize attribute holds the
number of records to be displayed in each page.
The property attribute of the column tag hold the value of the property to be
displayed in this each column. The value of the property can be any one of the
property of the ActorData class. The ActorData class should have a getter method for
that corresponding property. For instance if the property name is tvShow then their
should be a corresponding getTvShow() method in the ActorData class.
If the sortable attribute of the column tag is set to "true" then that column will be
sortable.
The group attribute of the column tag is set to "1" , which means each unique data
will be displayed only once and will not be repeated for the subsequent times.
The following image shows the first page of the data grid. Since the pagesize is set
to ten, ten records are displayed in the first page.

On clicking the Excel link the user will be prompted to open or save the file.
On clicking open the data grid will be displayed in Excel format.

The media property of the column tag is used to specify in which media that column
should be shown. If the media is set to "html" then only in the jsp page that
particular column will be displayed. If the media is set to "html, excel" then that
particular column will be displayed in jsp page as well as in excel.
1.<display:column property="tvShow" title="TV Show" sortable="true"
media="html" group="1" />
On clicking the PDF link the user will be prompted to open or save the file.
On clicking open the data grid will be displayed in PDF format.

On clicking the CSV link the data grid will be displayed in the csv format.
On clicking the XML link the data grid will be displayed in the xml format.

You can download the source code of the displaytag export to excel example by
clicking on the Download link below.

Struts File Upload


In this tutorial we will see how to allow the user to upload a file using Struts. In
order to allow the user to upload a file, we need to set the encoding type of
html:form tag to "multipart/form-data" and specify the HTTP method as "post".
The html:file tag enables the user to browse and select a file.
1.<html:form action="fileUploadAction" method="post" enctype="multipart/form-
data">
2.    File : <html:file property="file" /> <br/>
3.    <html:submit />
4.</html:form>

The property file in the FileUploadForm is of type FormFile


(org.apache.struts.upload.FormFile). We will check whether the file uploaded by the
user satisfies the following conditions in the FileUploadForm's validate() method.
Should be an Excel File.
File size should not exceed 20kb.

The validate() method of the FileUploadForm contains the following code.

01.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)


{
02.    ActionErrors errors = new ActionErrors();
03.    if (file.getFileSize() == 0) {
04.        errors.add("file", new ActionMessage("error.file.required"));
05.    } else if (!file.getContentType().equals("application/vnd.ms-excel")) {
06.        errors.add("file", new ActionMessage("error.file.type"));
07.    }
08.    /**
09.    * If the file size is greater than 20kb.
10.    */
11.    else if (file.getFileSize() > 20480) {
12.        errors.add("file", new ActionMessage("error.file.size"));
13.    }
14.    return errors;
15.}
The getFileSize() method returns the size of the file. The getContentType()
method returns the content type of the file selected by the user.
We save the file uploaded by the user in the server. To do this we first get the file
uploaded by the user using the getFile() method. The getFile() mehtod returns a
FormFile object. Using the FormFile object we can get details regarding the file like
file name and file data.
The FileUploadAction contains the following code.
01.public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
02.  FileUploadForm uploadForm = (FileUploadForm) form;
03.  FileOutputStream outputStream = null;
04.  FormFile formFile = null;
05.  try {
06.      formFile = uploadForm.getFile();
07.      String path = getServlet().getServletContext().getRealPath("")+"/"+
08.      formFile.getFileName();
09.      outputStream = new FileOutputStream(new File(path));
10.      outputStream.write(formFile.getFileData());
11.  } 
12.  finally {
13.      if (outputStream != null) {
14.          outputStream.close();
15.      }
16.  }
17.uploadForm.setMessage("The file "+formFile.getFileName()+" is uploaded
successfully.");
18.return mapping.findForward(SUCCESS);
19.}
The getFileData() method returns the entire file as a byte[]. This method should be
used only when the file size is small, incase of large files its better to use
getInputStream() method.
On executing the example the following page will be displayed to the user.

When the user submits the form without selecting any file the following message is
dispalyed to the user.

When the user selects a file other than an Excel file then the following message is
dispalyed to the user.

When the user selects a file that is greater than 20kb then the following message is
dispalyed to the user.
When the user selects an excel file that is less than 20kb, then the user is forwarded
to the success page.

Download the example and copy it inside the webapps directory of the Tomcat
sever.
Run the example using the following url "http://localhost:8080/Example23/".
Select an excel file to upload.
The excel file will be saved inside the Example directory in the server.

For example, when I uploaded the temp.xls file the file got stored in the
following location "C:\Program Files\Apache Software Foundation\Tomcat
5.5\webapps\Example23\temp.xls".
Multiple Struts Configuration Files Tutorial
Your struts-config.xml file is large and it is hard to maintain am I right? Not
anymore you can easily break it into multiple xml files like this.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
03.  <display-name>StrutsExample2</display-name>
04.  
05.  <servlet>
06.    <servlet-name>action</servlet-name>
07.    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
08.    <init-param>
09.      <param-name>config</param-name>
10.      <param-value>/WEB-INF/struts-config.xml, /WEB-INF/struts-
config2.xml</param-value>
11.    </init-param>
12.    <load-on-startup>2</load-on-startup>
13. </servlet>
14. <servlet-mapping>
15.    <servlet-name>action</servlet-name>
16.    <url-pattern>*.do</url-pattern>
17.  </servlet-mapping>
18.  
19.  <welcome-file-list>
20.    <welcome-file>index.jsp</welcome-file>
21.  </welcome-file-list>
22.</web-app>
By having multiple struts configuration files it will be easy to maintain and debug.
Here we work with a single module, so you can split the configuration file according
to your convenience. During the startup the ActionServlet will read all the
configuration files and create a database of configuration objects, which it will later
refer while processing the request.
Let's see how it works. The struts-config.xml files contains the following piece of
code.
01.<?xml version="1.0" encoding="ISO-8859-1" ?>
02.  
03.<!DOCTYPE struts-config PUBLIC
04.          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
05.          "http://struts.apache.org/dtds/struts-config_1_3.dtd">
06.  
07.<struts-config>
08.    <action-mappings>
09.       <action path="/sample1" type="com.vaannila.Sample1Action">
10.            <forward name="success" path="/sample1.jsp" />
11.       </action>
12.    </action-mappings>
13.</struts-config>
The struts-config2.xml file contains the following code.
01.<?xml version="1.0" encoding="ISO-8859-1" ?>
02.  
03.<!DOCTYPE struts-config PUBLIC
04."-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
05."http://struts.apache.org/dtds/struts-config_1_3.dtd">
06.  
07.<struts-config>
08.  
09.<action-mappings>
10.    <action path="/sample2" type="com.vaannila.Sample2Action">
11.        <forward name="success" path="/sample2.jsp" />
12.    </action>
13.</action-mappings>
14.  
15.</struts-config>
In the sample action classes we simply return "success". So according to the
configuration when the request URI is sample1 the user will be forwarded to
sample1.jsp and when the request URI is sample2 the user will be forwarded to the
sample2.jsp page.
Now let's try with the request URI sample1. In the index.jsp page we forward the
request to the URI sample1.
1.<jsp:forward page="sample1.do"/>
When you execute the application the sample1.jsp is displayed to the user.

In the same way you can try with the request URI sample2.
If you are working with multiple modules in your project, then you can have one
configuration file for each modules. Let's say the project has two modules admin and
reports. You access the admin screens using the URI admin/admin-module1 and
reports using the URI report/report-1. Here the admin and report are two different
modules. The following code shows how to create a seperate configuration file for
each module.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
03.  <display-name>StrutsExample2</display-name>
04.  
05.  <servlet>
06.    <servlet-name>action</servlet-name>
07.    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
08.    <init-param>
09.      <param-name>config/admin</param-name>
10.      <param-value>/WEB-INF/struts-config-admin.xml</param-value>
11.    </init-param>
12.    <init-param>
13.      <param-name>config/report</param-name>
14.      <param-value>/WEB-INF/struts-config-report.xml</param-value>
15.    </init-param>
16.    <load-on-startup>2</load-on-startup>
17. </servlet>
18.  
19.  <servlet-mapping>
20.    <servlet-name>action</servlet-name>
21.    <url-pattern>*.do</url-pattern>
22.  </servlet-mapping>
23.  
24.  <welcome-file-list>
25.    <welcome-file>index.jsp</welcome-file>
26.  </welcome-file-list>
27.</web-app>
Here the param-name should be config/moduleName and the param-value should be
the corresponding configuration file. If you have more than one file for that particular
module you can add them seperated by commas.
The struts configuration for admin module is done in the struts-config-admin.xml
file.
01.<?xml version="1.0" encoding="ISO-8859-1" ?>
02.  
03.<!DOCTYPE struts-config PUBLIC
04."-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
05."http://struts.apache.org/dtds/struts-config_1_3.dtd">
06.  
07.<struts-config>
08.<action-mappings>
09.    <action path="/admin1" type="com.vaannila.admin.AdminAction">
10.        <forward name="success" path="/admin.jsp"/>
11.    </action>
12.</action-mappings>
13.</struts-config>
In the AdminAction class we simply forward "success". The important thing to note
is that in the configuration file the value of the path attribute is /admin1 and to
invoke this we need to specify admin/admin1.do as the URI in the jsp page because
it is there inside the admin module.
In the jsp page.
1.<jsp:forward page="admin/admin1.do"/>
On executing the example the user will be forwarded to the admin.jsp page which
should be placed inside the admin directory.
The directory structure of the example look like this.

You can download the source code of this example by clicking on the Download link
below.

Вам также может понравиться