Writing the first Struts application
By: Norman Chap Printer Friendly Format
- Add relevant entries into the web.xml
a. Add ActionServlet Configuration with initialization
parameters
b. Add ActionServlet Mapping
c. Add relevant taglib declaration
- Start with a blank template for the struts-config.xml. In the
struts-config.xml, add the following
a. Declare the RequestProcessor
b. Create a properties file and declare it as Message Resource
Bundle
c. Declare the Message Resource Bundle
d. Declare the Form-bean
e. Declare the ActionMapping for the Form-bean
f. Add the forwards in the ActionMapping
- Create the Form-bean class
- Create the JSP with Struts tags
- Create the Action class
- For every <bean:message> tag in the JSP, add key value
pairs to the Message Resource Bundle (properties file) created in Step 2b
- Add Validation in the Form-bean
- Define the error messages in the Message Resource Bundle
- Create the rest of the JSPs.
Next, you will find the steps to build the Struts application.
You will find more explanation & rationale for the steps in the book Struts
Survival Guide.
1. Add relevant entries into the web.xm
web.xml for the Struts Application
<?xml version="1.0"
encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts
Application</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
</web-app>
2) Create the struts-config.xml
struts-config.xml for the Struts Application
<?xml version="1.0" encoding="ISO-8859-1"
?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration
1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="CustomerForm" type="struts.example.CustomerForm"/>
</form-beans>
<global-forwards>
<forward name="mainpage" path="index.jsp"
/>
</global-forwards>
<action-mappings>
<action path="/submitCustomerForm"
type="struts.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="CustomerForm.jsp">
<forward name="success" path="Success.jsp"
/>
</action>
</action-mappings>
<controller processorClass="org.apache.struts.action.RequestProcessor"/>
<message-resources parameter="struts.example.MessageResources"/>
</struts-config>
3) Create the ActionForm
CustomerForm
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() {
firstName = “”;
lastName = “”;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String s) {
this.firstName = s;
}
public String getLastName() {
return lastName;
}
public void setLastName(String s) {
this.lastName = s;
}
}
4) Create the CustomerForm JSP using Struts Tags
CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8"
language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld"
prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld"
prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message
key="exercise01.formpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<h2><bean:message
key="exercise01.formpage.title"/></h2>
<html:errors/>
<html:form action="/submitCustomerForm">
<bean:message key="prompt.customer.firstname"/>:
<html:text property="firstName" size="16"
maxlength="16"/>
<BR>
<bean:message key="prompt.customer.lastname"/>:
<html:text property="lastName" size="16"
maxlength="16"/>
<BR>
<html:submit property="step">
<bean:message key="button.save"/>
</html:submit>
<html:cancel>
<bean:message key="button.cancel"/>
</html:cancel>
</html:form>
</body>
</html:html>
5) Create the Action class
CustomerAction class
public class CustomerAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm
form,
HttpServletRequest request, HttpServletResponse response) throws
Exception
{
ActionForward nextPage = null;
if (isCancelled(request)) {
System.out.println("Cancel Operation Performed");
return mapping.findForward("mainpage");
}
CustomerForm custForm = (CustomerForm) form;
if ("Save".equals(custForm.getStep()))
{
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
System.out.println("Customer First name is " +
firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
}
return nextPage;
}
}
6) Add properties to MessageResources.properties
Message Resource Bundle
########################################
# Exercise01 index page strings
########################################
exercise01.indexpage.title=Welcome to Exercise01
########################################
# Exercise01 CustomerForm strings
########################################
exercise01.formpage.title=Please enter your details
prompt.customer.firstname=First Name
prompt.customer.lastname=Last Name
button.save=Save
button.cancel=Cancel
7) Add validation to the Form bean
validate() method for CustomerForm
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
// Firstname cannot be empty
if (firstName == null || firstName.trim().equals(""))
{
errors.add("firstName", new
ActionError("error.cust.firstname.empty"));
}
// Lastname cannot be empty
if (lastName == null || lastName.trim().equals("")) {
errors.add("lastName", new
ActionError("error.cust.lastname.empty"));
}
return errors;
}
8) Add ActionError keys to the Message Resources
ActionError keys to Message Resources
########################################
# Common
########################################
errors.header=<h3><font
color="red">Validation Error</font></h3>You must
correct the following error(s) before proceeding:<ul>
errors.footer=</ul><hr>
errors.prefix=<li>
errors.suffix=</li>
########################################
# Exercise01 CustomerForm ActionErrors
########################################
error.cust.firstname.empty=First Name is Required
error.cust.lastname.empty=Last Name is Required
9) Create the rest of the JSPs - index.jsp and Success.jsp. Notice that index.jsp uses the regular html:link tag that just forwards to another JSP. The Success.jsp uses the MVC compliant action mapping as the link. Define entries in MessageResource.properties for each of the bean:message keys in the JSPs.
index.jsp
<%@ page contentType="text/html;charset=UTF-8"
language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld"
prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld"
prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message
key="exercise01.indexpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<div align="center">
<html:link page="/CustomerForm.jsp">Go to
Customer Form</html:link>
</div>
</body>
</html:html>
Notice the usage of bean:write tags in Success.jsp. They let you access certain beans in appropriate scope and write their properties to the Servlet/JSP OutputStream
Success.jsp
<%@ page contentType="text/html;charset=UTF-8"
language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld"
prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld"
prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message
key="exercise01.successpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<h2><bean:message
key="exercise01.successpage.title" />
<bean:write name="CustomerForm" property="firstName"
/>
<bean:write name="CustomerForm" property="lastName"
/>
</h2>
<h3><bean:message
key="exercise01.successpage.message" /></h3>
<html:img src="images/beerchug.gif"/>
<html:link page="/showCustomerForm.do">Go
Back</html:link>
</body>
</html:html>
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Configuring JDBC DataSources in Struts
FAQ: Why was reload removed from Struts (since 1.1)?
FAQ: Why are my checkboxes not being set from ON to OFF?
Using JavaScript to submit a form in Struts
How to prepopulate a form in Struts
Simple example of using the requiredif Validator rule in Struts
When is the best time to validate input in Struts
What is a Plug-in and how to use Java plug-ins with Struts?
Origin and Architecture of Struts
Archived Comments
1. very helpful to me.thanks.very very useful to me.
View Tutorial By: viji at 2007-12-21 03:17:14
2. Thanks..
It is so easy to understand...
View Tutorial By: Rahul Meshram at 2008-09-11 13:18:41
3. Ya this is very fine.
View Tutorial By: Pradip at 2008-12-20 04:06:30
4. this has been copied from ram gopals holy book on
View Tutorial By: Manoj Kapil at 2009-02-10 11:38:45
5. i got really nice help from the code. Thanks.
View Tutorial By: Amit at 2009-04-10 08:18:40
6. Really help ful. To read abt jsp and servlet chk o
View Tutorial By: Raju at 2009-07-13 11:25:41
7. Very easy and simple to understand....good article
View Tutorial By: Ashish at 2009-10-07 00:58:08
8. Its tooo good to others.......& easy
View Tutorial By: Abhishek at 2010-03-31 23:57:07
9. Hi This is very fine to understanding struts flo
View Tutorial By: Abinash at 2011-06-28 08:27:18
10. Simple and easy to understand
View Tutorial By: Baji at 2011-09-10 18:24:48
11. Nice post. I am learning so much things from your
View Tutorial By: Umesh Kumar at 2012-03-15 11:16:24
12. This is very helpfull to us.........thnq
View Tutorial By: lavanya at 2012-03-17 05:43:12
13. its very helpful and understandable.thanq
View Tutorial By: Deepika darapaneni at 2012-03-24 14:16:39
14. Thank you I have understood the flow now.
<
View Tutorial By: Shyam at 2012-05-17 13:14:40
15. veryyyyyyyyyyy gooooooood tx.....................
View Tutorial By: eswar at 2012-06-19 08:23:36
16. waste of information...if u have gud information .
View Tutorial By: srujan at 2012-07-09 09:09:10
17. very nice content
View Tutorial By: sarat at 2012-08-22 12:17:26
18. Really appreciate, after a long time, I am able to
View Tutorial By: Senthil at 2012-09-16 06:03:15
19. I am new to this concept..It is really very useful
View Tutorial By: karthiga at 2013-01-02 11:20:38
20. The coding which is given is easy to understand bu
View Tutorial By: Chandra Sekhar Bodireddy at 2013-03-08 06:02:17
21. where i can find Messageressourse.properties......
View Tutorial By: sanjiv at 2013-09-07 06:59:19