Struts

Application- 9 :Creating a Struts Application used in Struts
Previous Home Next

Creating a Struts Application with Struts

In this chapter, you create a new Struts application for the purpose of using tag with Struts from start to end. tag generally used to take data form collection into application. For each piece of the application, we show you the code and then explain the code. This application design in NetBeans IDE- 6.8 with Struts 1.3.

Requirement for your struts application-

  • At least one view component is required in every Application.
  • A subclass of ActionForm is used to submit the date as application needed.
  • A subclass of Action class which provide specific processing functionality for the application.
  • A web.xml file is required for calling ActionServlet and struts-config.xml.
  • A struts-config.xml file is required for updating and mapping the update.

Let's Start the application, this application provide a good understanding how struts framework works and also understanding the development of Struts applications.

Now, Following the some steps for develop your first application name as GenException. GenException application contain following page-

  • Three View file name as index.jsp, search.jsp and sorry.jsp
  • One JavaBeans file name as searchForm.java, used for store data as application need.
  • one Action file name as searchAction.java, used for provide specific processing functionality.
  • In this application two other page name as EmployeData.java and Employee.java, are also make for handle and flow the data
  • Two XML file name as web.xml and struts-config.xml file, used for provide control, mapping and validation in application.

Step- 1 : Start your IDE ( NetBeans 6.8 with struts 1.3).

Step- 2 : Open a new project( Crtl+Shift+N), name it , add server( Apache Tomcat 6.0.20 ), then add struts framework 1.3 , and don't forget to add Struts TLDs.

Note:- When you click Finish button, your NetBeans IDE configure everything in place and project open in your IDE.

Step- 3: Open index.jsp page, from your struts application and code it as describe below.

<%--  Document: index.jsp
Description : First Page of GenException Application--%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" 
prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message key="welcome.title"/></title>
</head>
<body>
<h1 align="center"><bean:message
key="welcome.heading"/></h1>
<p align="center"><bean:message 
key="welcome.message"/></p>
<hr width="100%" size="+2" noshade="groove" 
style="color: blue">
<h2 align="center"> R4R Tech Soft Employee Partal</h2>
<hr width="80%" noshade="true">
<ul type="square">
<li><html:link forward="sorry"> 
Add an Employee Detail </html:link></li>
<li><html:link forward="search"> 
Search for Employees Detail </html:link></li>
<li><html:link forward="sorry"> 
Delete an Employee Delail </html:link></li>
</ul>
</body>
</html:html>

Step- 4: Open search.jsp page, from your struts application and code it as describe below.

<%--   Document: search.jsp
Description : Second Page of GenException Application--%>
<%@ taglib uri="http://struts.apache.org/tags-bean" 
prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" 
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" 
prefix="logic" %>
<html>
<head>
<title><bean:message key="welcome.title"/></title>
</head>
<body>
<h1 align="center"><bean:message
key="welcome.heading"/></h1>
<hr width="100%" size="+2" noshade="groove"
style="color: blue">
<h2 align="center"> R4R Tech Soft Employee Partal- 
Employee Search</h2>
<hr align="center" width="75%" noshade="true">
<html:errors/>
<strong style="color: blue"> Detail Search by either employee
name or employe Social Security Number</strong>
<html:form  method="post" action="/search">
<ul>
<table cellpadding="4" cellspacing="4">
<tr>
<td><bean:message key="welcome.first"/></td>
<td><html:text property="name" size="20"/></td>
</tr>
<tr>
<td></td>
<td> --- OR ---</td>
</tr>
<tr>
<td><bean:message key="welcome.number"/></td>
<td><html:text property="ssNum" size="20"/> &equiv; 
(x-xxx-xx-xxxx)</td>
</tr>
<tr>
<td></td>
<td><html:submit value=" Submit Query "/></td>
</tr>
</table>
</ul>
</html:form>

<logic:present name="searchForm" property="results">

<hr width="100%" size="+1" noshade="true">
<hr width="100%" size="+1" noshade="true">

<bean:size id="size" name="searchForm" property="results"/>

<%--  If Logic value>0, then return the value  --%>
<logic:greaterThan name="size" value="0">
<strong><u>Check Search Details</u></strong><BR><BR>
<table border="1">
<tr>
<th> Employee Name </th>
<th>Social Security Number</th>
<th> Department </th>
<th> Date Of Joining </th>
</tr>
<logic:iterate id="result" name="searchForm"
property="results">
<tr>
<td><bean:write name="result" property="name"/></td>
<td><bean:write name="result" property="ssNum"/></td>
<td><bean:write name="result" property="dept" /></td>
<td><bean:write name="result" property="dated" /></td>
</tr>
</logic:iterate>
</table>
<p> Query Search on <strong><bean:write
name="searchForm" property="date" /></strong>
at the time <strong><bean:write 
name="searchForm" property="time" /></strong> </p>
</logic:greaterThan>
</logic:present>
</body>
</html>

Step- 5: Open sorry.jsp page, from your struts application and code it as describe below.

<%--  Document: search.jsp
Description : Third Page of GenException Application--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" 
prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message key="welcome.title"/></title>
</head>
<body>
<h1 align="center"><bean:message 
key="welcome.heading"/></h1>
<hr width="100%" size="+2" noshade="groove" 
style="color: blue">
<h1>We apologize for the inconvenience!
Page not ready yet</h1>
<ul>
Return to <html:link forward="home"> home </html:link> page
</ul>

</body> </html:html>

Step- 6: Open web.xml file place in WEB-INF folder, this file is used to map the ActionServlet( work as backbone of application, every Action, Validation and ActionForm class control by this class) , struts-config.xml file, welcome file and five different TagLibrary.

<!-- Save as a web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<!-- ActionServlet map here, however you can't find
this class within the project but it work as a backbone 
of the project -->
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action
.ActionServlet</servlet-class>
<!-- Your struts-config.xml file map here-->
<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>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Action class map with URL -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<!-- Welcome file map here: -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<!-- All the Tag Library which used with in the project -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld
</taglib-location>
</taglib>
<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-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld
</taglib-location>
</taglib>
</jsp-config>
</web-app>

Step- 7: Open struts-config.xml file place in WEB-INF folder, this file is used to map Model class, Exception class, Validation class, Action class( Action class further choose View class) and ApplicationResource class.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//
DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="searchForm" 
type="r4r.searchForm"/>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
<forward name="search" path="/search.jsp"/>
<forward name="sorry" path="/Sorry.jsp" />
<forward name="home" path="/index.jsp" />
</global-forwards>
<action-mappings>
<action input="/search.jsp" name="searchForm" 
path="/search"
scope="request" type="r4r.SearchAction">
<exception key="error.NoResultsFoundException" 
path="/exception.jsp" 
type="java.lang.NoResultsFoundException"/>
</action>
</action-mappings>
<controller processorClass="org.apache.struts
.tiles.TilesRequestProcessor"/>
<message-resources parameter="com/myapp
/struts/ApplicationResource"/>
<!-- ========== Tiles plugin ==========-->
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config" 
value="/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
</plug-in>
<!-- ========== Validator plugin ========== -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
  property="pathnames"
  value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>

Step- 8: Now introduce Bean class into struts-config.xml file, As we define earlier, about how to introduce Bean and Action class in the struts-config.xml file. Now, Bean class of GenException application is

/* Save as a searchForm.java */
package r4r;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/* @author Sachin */
public class searchForm extends 
	org.apache.struts.action.ActionForm {
 private String name = null;
    private String ssNum = null;
    private List results = null;
    private String date, time;
	public void setName(String name) {
        this.name = name;
 }
    public String getName() {
        return name;
    }
    public void setSsNum(String ssNum) {
        this.ssNum = ssNum;
    }
    public String getSsNum() {
        return ssNum;
    }
    public void setResults(List results) {
        this.results = results;
    }
    public List getResults() {
        return results;
    }
    //GET date in dd/mm/yyyy formate
    public String getDate() {
        StringBuffer date = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        date.append(calendar.get(Calendar.DAY_OF_MONTH));
        date.append("/");
        date.append(calendar.get(Calendar.MONTH) + 1);
        date.append("/");
        date.append(calendar.get(Calendar.YEAR));
        return date.toString();
    }
    public void setDate(String date) {
        this.date = date;
    }
    //GET Time in HH/MM/SS formate
    public String getTime()
	StringBuffer time = new StringBuffer();
    Calendar calendar = Calendar.getInstance();
    time.append(calendar.get(Calendar.HOUR));
        time.append(":");
        time.append(calendar.get(Calendar.MINUTE));
        time.append(":");
        time.append(calendar.get(Calendar.SECOND));
    return time.toString();
    }
    public void setTime(String time) {
        this.time = time;
    }
    // Reset  all form fields.
    @Override
    public void reset(ActionMapping mapping,
	HttpServletRequest request) {
        name = null;
        ssNum = null;
        results = null;
    }
    // Validate form data.
    @Override
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        boolean nameEntered = false;
        boolean ssNumEntered = false;
        // Determine if name has been entered.
        if (name != null && name.length() > 0) {
            nameEntered = true;
        }
        /* Determine if social security number 
		has been entered.*/
        if (ssNum != null && ssNum.length() > 0) {
            ssNumEntered = true;
        }
        /* Validate that either name or social security
		number has been entered. */
        if (!nameEntered && !ssNumEntered) {
           errors.add(null, new ActionMessage
			   ("error.search.criteria.missing"));
        }
        /* Validate format of social security number if
        it has been entered. */
        if (ssNumEntered && !isValidSsNum(ssNum.trim())) {
            errors.add("ssNum", new ActionMessage
				("error.search.ssNum.invalid"));
        }
        return errors;
    }
    // Validate format of social security number.
           private static boolean isValidSsNum(String ssNum) {
        if (ssNum.length() < 13) {
            return false;
        }
        for (int i = 0; i < 13; i++) {
            if (i == 1 || i == 5 || i == 8) {
            if (ssNum.charAt(i) != '-') {
                    return false;
                }
            } else if 
				("0123456789".indexOf(ssNum.charAt(i)) == -1) {
                return false;
            }
        }
        return true;
    }
}            

Step- 9: Action class of GenException application is

/*
 * Save as a SearchAction.java
 */
package r4r;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SearchAction extends org.apache
	.struts.action.Action {
/* forward name="success" path="" */
private static final String
	SUCCESS = "success";
/* This is the action called from the Struts framework.
 * @return */
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form,HttpServletRequest request, 
HttpServletResponse response)throws Exception {
//Create a new Employee data page
EmployeDate data = new EmployeDate();
ArrayList results;
//Call the search form here:
searchForm searchForm = (searchForm) form;
String name = searchForm.getName();
/*Perform employee search based on what 
criteria was entered.*/
if (name != null && name.trim().length() > 0) {
results = data.searchByName(name);
} else {
results = data.searchBySsNum(searchForm.getSsNum().trim());
}
/* Throw an application exception if results were
not found.*/
if (results.size() < 1) {
throw new NoResultsFoundException();
}
/* Now, Place search results in SearchForm,
and access by JSP page.*/
searchForm.setResults(results);
/* All condition true, then Forward control to
XML mapping.*/
return mapping.getInputForward();
}
}
--> EmployeData.java page 
/* Save as a EmployeDate.java
 * This page is call by Action class */
package r4r;
import java.util.ArrayList;
public class EmployeDate {
/* This is part of dataBase(insert, query and update)
/* Utilized collection part(List) for Hardcore data */
private static Employee[] employees = {
new Employee("RituRaj Tyagi", "0-000-00-0000",
	"Computer", "10-01- 2010"),
new Employee("Rajesh Patel", "1-111-11-1111", 
	"Computer", "10-01- 2010"),
new Employee("Ankit Tyagi", "2-222-22-2222", 
	"IT ", "08-05- 2010"),
new Employee("Sachin Tyagi", "4-444-44-4444",
	"Electronic", "12-06- 2010"),
new Employee("Sunny Tyagi", "5-555-55-5555", 
	"Electronic", "22-09- 2010"),
new Employee("Binny Tyagi", "6-666-66-6666", 
	"IT", "17-08- 2010")
};
// Search for employees by name.
public ArrayList searchByName(String name) {
ArrayList resultList = new ArrayList();

for (int i = 0; i < employees.length; i++) {
if (employees[i].getName().toUpperCase()
	.indexOf(name.toUpperCase()) != -1) {
resultList.add(employees[i]);
}
}
return resultList;
}
// Search for employee by social security number.
public ArrayList searchBySsNum(String ssNum) {
ArrayList resultList = new ArrayList();
for (int i = 0; i < employees.length; i++) {
if (employees[i].getSsNum().equals(ssNum)) {
resultList.add(employees[i]);
}
}
return resultList;
}
}
--> Employee.java 
/ *  Save as a Employee.java*/
/ * Page call by EmployeeData.java */
package r4r;
/* Getter/ Setter property of Employee data */
public class Employee {
private String name, ssNum, dept, dated;
public Employee(String name, String ssNum,
	String dept, String dated) {
this.name = name;
this.ssNum = ssNum;
this.dept = dept;
this.dated = dated;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSsNum(String ssNum) {
this.ssNum = ssNum;
}
public String getSsNum() {
return ssNum;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getDated() {
return dated;
}
public void setDated(String dated) {
this.dated = dated;
}
}

 

Run your application:

Now your application is complete, so now start run your application. Start your server( which you embedded when configure our struts application), then right click your application and click upon Run option or open your welcome( index.jsp) page and press shift+F6.

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: