Java J2ee Tutorials

Showing posts with label Struts Example. Show all posts
Showing posts with label Struts Example. Show all posts

Writing the first Struts Application

Friday, August 31, 2012

Let's start with developing your first Struts application. Here are the steps involved in creating the Struts application.

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.xml

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>

Free Career Predictions

Struts: Structuring a Web Application

Saturday, March 24, 2012

Web application as a program that resides on a Web server and produces dynamically or static created pages in a hypertext markup language (most commonly HTML) in response to a user’s request. A user make request by clicking the link or button on the web page. To built the Web application, Java 2 Enterprise Edition (J2EE) must be used.

Web Container :

A web container is a program that manages the components of a Web application, in particular JSP pages and Java Servlets. A Web container provides a number of services, such as
  • Life-Cycle management: Web container provide the process of starting up and shutting down a component.
  • Concurrency: Provide the capability to process more than one action at a time.
  • Security : Provide the restricted access to components, such as username & password protection.
  • Portability: Access anywhere, taking very less resource.
  • Apache Tomcat & GlassFish Server are the example of a Web container, — an open-source implementation of the J2EE Java Servlet and JavaServer Pages (JSP) specifications. A specification is a document that describes all the details of a technology. Typically, a Web container also functions as a Web server, providing basic HTTP (Hypertext Transfer Protocol) support for users who want to access information on the site.

Structuring a Web Application

Free Career Predictions

Struts Example

Friday, March 23, 2012

Struts is modeled after the MVC design pattern, you can follow a standard development process for all of your Struts Web applications.

Identificaty of the application Views, the Controller objects that will service those Views, and the Model components being operated on.

1. Define and create all of the Views, in relation to their purpose, that will represent the user interface of our application. Add all ActionForms used by the created Views to the struts-config.xml file.
2. Create the components of the application’s Controller.
3. Define the relationships that exist between the Views and the Controllers (struts-config.xml).
4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Web application.

Lets Start with step one. we will create the view file named index.jsp

index.jsp
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
Sample Struts Application
Name:

We have used some Struts-specific Form tag like instead of HTML tags.

In the Form tags the attributes you can find some attributes defined in we will go through it.

action : Represents the URL to which this form will be submitted. This attribute is also used to find the appropriate ActionMapping in the Struts configuration file, which we will describe later in this section. The value used in our example is Name, which will map to an ActionMapping with a path attribute equal to Name.

name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data between View and Controller components. We will discuss NameForm later in this section.
type :Names the fully qualified class name of the form bean to use in this request. For this example, we use thevalue example.NameForm, which is an ActionForm object containing data members matching the inputs of this form.

To use the HTML tags, you must first add a taglib entry in the application’s web.xml file that references the URI /WEB-INF/struts-html.tld. This TLD describes all of the tags in the HTML tag library. The following snippet shows the element that must be added to the web.xml file:

/WEB-INF/struts-html.tld
/WEB-INF/struts-html.tld

The struts-html.tld is placed in the /WEB_INF directory.

Next Step is to create the action form

The ActionForm used in this example contains a single data member that maps directly to the nameinput parameter of the form defined in the index.jsp View. When an is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered into the tags. The Struts framework does this by using JavaBean reflection. The accessors of the ActionForm must follow the JavaBean standard naming convention for example

private String name;
public void setName(String name);
public String getName();

The NameForm.java file is shown below
NameForm.java

package example;
//import statements
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class NameForm extends ActionForm {
private String name = null;
public String getName() {
return (name);
}
public void setName(String name) {
this.name = name;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name = null;
}
}

To deploy the NameForm to our Struts application, you need to compile this class, move it to the /WEB-INF/classes/example directory, and add the following line to the section of the /WEB-INF/struts-config.xml file:



This makes the Struts application aware of the NameForm and how it should be referenced.

Now we create the out page for the sample application.
Lets name it diplayname.jsp
displayname.jsp



Sample Struts Display Name

Hello <%= request.getAttribute("NAME") %> !!


Now we move to the step two of creating the application's controller

In a Struts application, two components make up the Controller. These two components are theorg.apache.struts.action.ActionServlet and the org.apache. struts.action.Action classes. In most Struts applications, there is one org. apache.struts.action.ActionServlet implementation and can have many org.apache. struts.action.Action implementations.

The org.apache.struts.action.ActionServlet is the Controller component that handles client requests and determines which org.apache.struts.action.Action will process the received request. When assembling simple applications, such as the one we are building, the default ActionServlet will satisfy your application needs, and therefore, you do not need to create a specializedorg.apache.struts.action.ActionServlet implementation.

The second component of a Struts Controller is the org.apache.struts. action.Action class. As opposed to the ActionServlet, the Action class must be extended for each specialized function in your application. This class is where your application’s specific logic begins.
NameAction.java

package example;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class NameAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String target = new String("success");
if ( form != null ) {
// Use the NameForm to get the request parameters
NameForm nameForm = (NameForm)form;
String name = nameForm.getName();
}
// if no mane supplied Set the target to failure
if ( name == null ) {
target = new String("failure");
}
else {
request.setAttribute("NAME", name);
}
return (mapping.findForward(target));
}
}


Moving to step three, to deploy the NameAction to our Struts application, we need to compile the NameAction class and move the class file to /WEB-INF/classes/example directory, and add the following entry to the section of the /WEB-INF/struts-config.xml file:


For step four we modify the web.xml file. We have to to tell the Web application about our ActionServlet. This is accomplished by adding the following servlet definition to the /WEB-INF/web.xml file:

action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
1

Once we have told the container about the ActionServlet, we need to tell it when the action should be executed. To do this, we have to add a element to the /WEB-INF/ web.xml file:

action
*.do

You will notice in the previously listed index.jsp that our action does not include a .do at the end of the URL. We do not have to append the .do because it is automatically appended if we use the tag. If you do not use the tag, then you will need to append .do to the action's URL. This mapping tells the Web application that whenever a request is received with .do appended to the URL, the servlet named action should service the request.

Free Career Predictions