Struts MVC Architecture
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 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.
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.
The country and the state dropdowns are populate with the values present in the
array list.
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.
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.
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.
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
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
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.
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
On clicking the Excel link in the user.jsp page. The userDetails.jsp page will be
displayed in the Excel fromat.
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
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.
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.