Writing the first Struts application

By: Norman Chap Emailed: 1605 times Printed: 2077 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Let's start with developing your first Struts application. Here are the steps involved in creating the Struts application.
  1. Add relevant entries into the web.xml

    a. Add ActionServlet Configuration with initialization parameters
    b. Add ActionServlet Mapping
    c. Add relevant taglib declaration
  2. 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
  3. Create the Form-bean class
  4. Create the JSP with Struts tags
  5. Create the Action class
  6. For every <bean:message> tag in the JSP, add key value pairs to the Message Resource Bundle (properties file) created in Step 2b
  7. Add Validation in the Form-bean
  8. Define the error messages in the Message Resource Bundle
  9. 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>
&nbsp;
<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>


Struts Home | All Struts Tutorials | Latest Struts Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(17)


1. View Comment

very helpful to me.thanks.very very useful to me.

View Tutorial          By: viji at 2007-12-21 03:17:14
2. View Comment

Thanks..
It is so easy to understand...


View Tutorial          By: Rahul Meshram at 2008-09-11 13:18:41
3. View Comment

Ya this is very fine.

View Tutorial          By: Pradip at 2008-12-20 04:06:30
4. View Comment

i got really nice help from the code. Thanks.

View Tutorial          By: Amit at 2009-04-10 08:18:40
5. View Comment

Really help ful. To read abt jsp and servlet chk out my link.

View Tutorial          By: Raju at 2009-07-13 11:25:41
6. View Comment

Very easy and simple to understand....good article for people starting out with struts

View Tutorial          By: Ashish at 2009-10-07 00:58:08
7. View Comment

Its tooo good to others.......& easy

View Tutorial          By: Abhishek at 2010-03-31 23:57:07
8. View Comment

Hi This is very fine to understanding struts flow

View Tutorial          By: Abinash at 2011-06-28 08:27:18
9. View Comment

Nice post. I am learning so much things from your website and getting good information compared to other websites

View Tutorial          By: Umesh Kumar at 2012-03-15 11:16:24
10. View Comment

This is very helpfull to us.........thnq

View Tutorial          By: lavanya at 2012-03-17 05:43:12
11. View Comment

its very helpful and understandable.thanq

View Tutorial          By: Deepika darapaneni at 2012-03-24 14:16:39
12. View Comment

Thank you I have understood the flow now.


-


View Tutorial          By: Shyam at 2012-05-17 13:14:40
13. View Comment

very nice content

View Tutorial          By: sarat at 2012-08-22 12:17:26
14. View Comment

Really appreciate, after a long time, I am able to recollect struts stuff easily. thanks a lot.

View Tutorial          By: Senthil at 2012-09-16 06:03:15
15. View Comment

I am new to this concept..It is really very useful for me to develop a strut framework concept..Thanks a lot..

View Tutorial          By: karthiga at 2013-01-02 11:20:38
16. View Comment

The coding which is given is easy to understand but I found one thing is missing in CustomerForm i.e custForm.getStep() which is been used in CutomerAction. Please modify the code.

View Tutorial          By: Chandra Sekhar Bodireddy at 2013-03-08 06:02:17
17. View Comment

where i can find Messageressourse.properties......
and getting error cannot find symbol class ActionError while i hve imported specific package.
please reply?


View Tutorial          By: sanjiv at 2013-09-07 06:59:19

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Norman Chap
The break Statement example in Java
Stored Procedures example in SQL
JDBC and Tomcat context settings
File read and write - sample program in C
Pointers and Function Arguments in C
Writing the first Struts application
goto and labels in C
External Variables and Scope in C
Multiple inheritance example in C++
qsort() sample program in C++
Image and ImageItem sample program in J2ME
SimpleDateFormat sample program in Java
Observable class and the sample program in Java

More Tutorials in Struts
Configuring JDBC DataSources in Struts
Struts Classes
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
Chaining actions 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?
7 Best Practices of Struts
Origin and Architecture of Struts
ActionErrors and ActionError in Struts
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling multiple buttons in HTML Form in Struts

More Latest News
Most Viewed Articles (in Struts )
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling Duplicate Form Submissions in Struts
What is Struts? Which Version of Struts to use?
Model 1 Architecture
ForwardAction in Struts
Editing web.xml in a Struts Application
Struts 1 vs Struts 2
MVC Architecture (Model 2 Architecture)
Writing the first Struts application
ActionErrors and ActionError in Struts
What is a Plug-in and how to use Java plug-ins with Struts?
FAQ: Why are my checkboxes not being set from ON to OFF?
What is a Model View Controller (MVC) Model?
Configuring JDBC DataSources in Struts
Struts Classes
Most Emailed Articles (in Struts)
What is Struts? Which Version of Struts to use?
Use ImageButtonBean for Image based Form Submits in Struts
WebWork 2 is now Apache Struts 2
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Simple example of using the requiredif Validator rule in Struts
Is Struts the most popular web application framework for Java?
What is a Model View Controller (MVC) Model?
Struts 1 vs Struts 2
Using Multibox in Struts
Using Multiple Message Resource Bundles in Struts
ForwardAction in Struts
IncludeAction in Struts
FAQ: Why was reload removed from Struts (since 1.1)?
Handling multiple buttons in HTML Form in Struts