Monday, November 28, 2011

Struts 2.2.3 Hello world example with Eclipse


I have been looking for a full flash working example of a struts 2.2.3.1 So I Googled it. And found some examples. But all of them were either uncomplete or using older version of struts. So I decided to make my own.
To make a struts 2 hello world example I created an example in which user simply puts some information on the form submits it and on submission user gets informed that his form has been processed.
Prerequisites:
  •        Any Web/application server : (I used tomcat 6)  Tomcat , JBoss etc.
  •        Struts library : can be downloaded from Here or go to struts official site.
  •               Eclipse IDE for easier configuration of project Europa or above.
  •        Fundamental knowledge of Eclipse is preferable.
      For a newbie it is suggested that to read some struts fundamentals. Like what is the basic structure of Struts application. Basically in a struts Web application you need to configure your bean class, filter dispatcher and actions. Basic structure of a struts application that is made is follows.

 
Struts project structure in eclipse
For those who are familiar with Eclipse’s environment then this structure is easily understandable. For those who are new at this ! don’t worry. Just follow the steps provided and you should get your application running.
Step 1. Open eclipse and create new ‘Dynamic Web Project’ With any suitable name.  I gave Struts Practice3 here. 
Configure your Tomcat server before you proceed building any Web application as we gonna need that to run out application.
Step 2. Fundamental structure of a web application will be created by eclipse. After that you need to copy your necessary struts library files into your application’s lib folder.
Following is the list that are necessary library files required to run struts 2.2.3 application.
After a 2 hour long search and debugging I found the list that is actually required to run a struts application
1. Commons-fileupload-1.2.2.jar
2. Commons-io-2.0.1.jar
3. Commons-logging-1.1.1.jar
4. Commons-logging-api-1.1.jar
5. Freemarker-2.3.1.6.jar
6. Javassist-3.11.0.GA.jar
7. Ognl-3.0.1.jar
8. Struts2-core-2.2.3.1.jar
9. Xwork-core-2.2.3.1.jar
Don’t worry about the exact version names. They are all bundled with struts distribution. Copy those files from the struts distribution package and paste them in to the lib folder . As shown in the picture.
Step3. Next thing is to configure our web.xml file So here is the web.xml code. What we are telling here is that there is an application with the name StrutsPractice3 Which if we run on server then all requests will be filtered through FilterDispatcher. (You can ignore security constraint here its optional. Its just to make sure that Jsp files are not directly accessible.)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>StrutsPractice3</display-name>
 
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>JSPs</web-resource-name>
      <url-pattern>/jsp/*</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
  </security-constraint>
  <login-config>
    <auth-method>BASIC</auth-method>
  </login-config>
  <filter>
    <display-name>struts2</display-name>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


Step 4. Now our filter dispatcher will look for its struts.xml file. So its time to configure it . So here is the code.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="app" extends="struts-default" namespace="/">
              <action name="Product_input">
                     <result>/jsp/ProductForm.jsp</result>
              </action>
              <action name="Product_save" class="app.Product">
                     <result>/jsp/ProductDetails.jsp</result>
              </action>
       </package>
</struts>
As you can see It has two actions defined.  Product_input and Product_save. Product_input doesn’t have any class so struts will just forward request to ProductForm.jsp (we’ll make is very soon.) and in Product_details action the class Product in app package is defined. As there is not method specified here so it will find execute method by default defined in Product class.
Setp 5. Next step is to define Product Class. So right click on project and create a package with the name app. Then again right click on package and create new java class with name Package. Define three private variables productName, description, price with getter and setter methods  and a public method execute. Here is the code.  (To create getter setter methods right click on class go to Source -> generate getter setters and eclipse create getter and setter methods for you.)
package app;
import java.io.Serializable;
import com.opensymphony.xwork2.ActionSupport;
public class Product extends ActionSupport implements Serializable {
                private String productName;
                private String description;
                private String price;
                public String execute(){
                                System.out.println("Hello world");
                                return "success";
                }
                public String getProductName() {
                                return productName;
                }
                public void setProductName(String productName) {
                                this.productName = productName;
                }
public String getDescription() {
                                return description;
                }
                public void setDescription(String description) {
                                this.description = description;
                }
                public String getPrice() {
                                return price;
                }
                public void setPrice(String price) {
                                this.price = price;
                }
}
Step 5. Now last step is to create our view part. i.e. the jsp files.
Right click on WebContent folder create new folder with the name jsp (Its not necessary to create files in a folder. If you don’t want to use it then just create jsp files in WebContent. But then adjust jsp path in struts.xml file) inside jsp folder create new jsp files with name
ProductForm.jsp and ProductDetails.jsp

ProductForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Input Form</title>
</head>
<body>
<h3>Product input form</h3>

<s:form action="Product_save.action" method="post">
<table>
<tr><td><s:textfield name="productName" label="Product Name" /></td></tr>
<tr><td><s:textfield name="description" label="Product Description"/></td></tr>
<tr><td><s:textfield name="price" label="Product Price"/></td></tr>
<tr><td><s:submit align="center" /><s:reset name="Reset" value="Reset"/></td></tr>
</table>
</s:form>
</body>
</html>

ProductDetails.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Product Details are follows</h3>
<p>
Product Name: <s:property value="productName"/><br/>
Description: <s:property value="description"/><br/>
Price: $ <s:property value="price"/>
 </p>
</body>
</html>

That’s it ..!! you just created a struts application.
No run the application on server. (Start tomcat, Export project as war file into tomcat’s webapp directory) and try accessing following url

Please give your valuable response if that article was helpful.






1 comment:

  1. Nice tutorial using Struts 2 with good images. I have a Basic Struts Login Application program using Strus1.2. I think this will also very helpful to your blog followers.

    ReplyDelete

Leave your comment here....