Java J2ee Tutorials

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

What Is the Struts Framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

  • Open source
  • Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:

    • Model: application state
    • View: presentation of data (JSP, HTML)
    • Controller: routing of the application flow
  • Implements the JSP Model 2 Architecture
  • Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.

The diagram below describes the flow in more detail:

  1. User clicks on a link in an HTML page.
  2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.
  3. Action makes a call to a Model layer service.
  4. Service makes a call to the Data layer (database) and the requested data is returned.
  5. Service returns to the action.
  6. Action forwards to a View resource (JSP page)
  7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
  8. JSP file is invoked and sent to the browser as HTML.
  9. User is presented with a new HTML page in a web browser.

Free Career Predictions

Differences Between Struts1 and Struts2

The table given below describes some differences between struts1 and struts2

Feature
Struts 1
Struts 2
Action classes
Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces. While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object.
Threading Model
Struts 1 Actions are singletons therefore they must be thread-safe because only one instance of a class handles all the requests for that Action. The singleton strategy restricts to Struts 1 Actions and requires extra care to make the action resources thread safe or synchronized while developing an application. Struts 2 doesn't have thread-safety issues as Action objects are instantiated for each request. A servlet container generates many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.
Servlet Dependency
Actions are dependent on the servlet API because HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked therefore Struts1. Container does not treat the Struts 2 Actions as a couple. Servlet contexts are typically represented as simple Maps that allow Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. While other architectural elements directly reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse.
Testability


Struts1 application has a major problem while testing the application because the execute method exposes the Servlet API. Struts TestCase provides a set of mock object for Struts 1.
To test the Struts 2 Actions instantiate the Action, set the properties, and invoking methods. Dependency Injection also makes testing easier.
Harvesting Input
Struts 1 recieves an input by creating an ActionForm object. Like the action classes, all ActionForms class must extend a ActionForm base class. Other JavaBeans classes cannot be used as ActionForms, while developers create redundant classes to receive the input. DynaBeans is the best alternative to create the conventional ActionForm classes. Struts 2 requires Action properties as input properties that eliminates the need of a second input object. These Input properties may be rich object types, since they may have their own properties. Developer can access the Action properties from the web page using the taglibs. Struts 2 also supports the ActionForm pattern, POJO form objects and POJO Actions as well.
Expression Language
Struts1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views
Struts 1 binds objects into the page context by using the standard JSP mechanism. Struts 2 uses a ValueStack technology to make the values accessible to the taglibs without coupling the view to the object to which it is rendering. The ValueStack strategy enables us to reuse views across a range of types, having same property name but different property types.
Type Conversion
Struts 1 ActionForm properties are almost in the form of Strings. Commons-Beanutils are used by used by Struts 1 for type conversion. Converters are per-class, which are not configurable per instance. Struts 2 uses OGNL for type conversion and converters to convert Basic and common object types and primitives as well.
Validation
Struts 1 uses manual validation that is done via a validate method on the ActionForm, or by using an extension to the Commons Validator. Classes can have different validation contexts for the same class, while chaining to validations on sub-objects is not allowed. Struts 2 allows manual validation that is done by using the validate method and the XWork Validation framework. The Xwork Validation Framework allows chaining of validations into sub-properties using the validations defined for the properties class type and the validation context.
Control of Action Execution
Each module in Struts 1 has a separate Request Processors (lifecycles), while all the Actions in the module must share the same lifecycle. In Struts 2 different lifecycles are created on a per Action basis via Interceptor Stacks. Custom stacks are created and used with different Actions, as required.s

Free Career Predictions

Download and Install Hibernate

Saturday, August 18, 2012

Let us see what are the jar files we need to download to work with hibernate framework, and how to install.

Working with the framework software is nothing but, adding the .jar(s) files provided by that framework to our java application. Each framework software is not an installable software, it means we do not contain any setup.exe
When we download any framework software, we will get a ‘zip‘ file and we need to unzip it, to get the jar files required, actually all framework softwares will follow same common principles like:


  • Framework software will be in the form of a set of jar files, where one jar file acts as main (We can call this file as core) and remaining will acts as dependent jar files.
  • Each Framework software contain at least one configuration xml file, but multiple configuration files also allowed.
  • In this case, in order to setup the Hibernate framework environment into a java application, the configuration file is the first one to be loaded into a java application, will see about this in later sessions.


Download Hibernate .jar(s) files:
we can download jars related to hibernate at http://sourceforge.net/projects/hibernate/files/hibernate3

  • From the above URL choose hibernate 3.2.2-ga.zip, as we are in initial stage this version will be better.
  • Unzip it, and now you can find some jar files in the lib folder right.?, actually we doesn’t require all the jar files, out of them just select the following jar files :

Anttr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
ehcash.jar
dom4j-1.6.1.jar
hibernate3.jar
jta.jar
log4j-1.2.3.jar

  • These are the main jar files to run hibernate related programming and among all the jars hibernate3.jar is the main file, but for annotation we need to add 4 – 6 other jar files, i will let you when time comes.
  • Remember: along with the hibernate jars we must include one more jar file, which is nothing but related to our database, this is depending on your database.
  • So finally we need total of 12 jar files to run the hibernate related program.

Free Career Predictions

EClipse Directory Structure


  • WebContent: Regular Web files (HTML, JavaScript, CSS, JSP, images, etc.)
  • WebContent/some-subdirectory: Web files in subdirectory.
  • WebContent/WEB-INF: web.xml (used for servlet mappings)
  • WebContent/WEB-INF/lib: JAR files specific to application.
  • src/(default package): Unpackaged (default package) Java code. Using the default package is generally a bad choice in Web apps.
  • src/somePackage: Java code in somePackage package.
  • Note: You can cut/paste or drag/drop existing files into appropriate locations, but it is hard to drag files into a Java package until you create at least one class first.

Free Career Predictions