How to configure & create sample struts 2 project in eclipse? A Step by Step guide.

In this article, let us see step by step guide to configure struts 2 in eclipse and create a sample web application.
The requirements to start a strut2 project are

1. Struts 2 Jars
2. Java requirements : Java 1.5 or above , Servlet API 2.4 or above , JSP API 2.0 or above
3. Latest Eclipse with Apache Tomcat server

First let us see how to configure struts 2 for your new web application

1. Add struts2 jars to java build path. Download struts 2 full distribution (struts-2.3.16.3-all.zip) and extract the same in a folder that has many jars in the lib folder.  Jars required for your project may vary depending upon your project requirement.

Minimum jars required for any struts 2  web project creation.
1. struts2-core-2.3.16.3.jar
2. commons-logging-1.1.3.jar
3. commons-logging-api-1.1.jar
4. commons-lang3-3.1.jar
5. freemarker-2.3.19.jar
6. ognl-3.0.6.jar
7. commons-fileupload-1.3.1.jar
8. commons-io-2.2.jar
9. javassist-3.11.0.GA.jar
10. xwork-core-2.3.16.3

2. Other than jars, minimum files required are to start with struts2 project.
1. Web.xml
2. struts.xml

i) Configure web.xml for defining filter class of your struts2 web application. In struts2, all the requests made to the web application is routed through a Filter class to handle. If you are using latest version of struts2 i.e 2.3.16 or above, use StrutsPrepareAndExecuteFilter class. or use FilterDispatcher which is depreciated.

ii) Create mapping with struts.xml. Any struts2 web project will have model , action class (controller) and view page (MVC). Mapping between actions and views are configured in struts.xml file. Don’t forget to copy the struts.xml in /WEB-INF/Classes folder OR  you can put it  in src folder which will be placed in classes folder at run time.

You can see the directory and files  structure of the sample project below.sample project structure

Now let us create sample project in struts2. (In our example Struts2Sample that contains Index.jsp , GetEmployeeCode.jsp and Display.jsp which accepts code, name, designation, email and mobile.)

1. Copy all the above jars to lib folder under /Struts2Sample/WebContent/WEB-INF/ in your Struts2Sample project and refresh lib folder in eclipse. or the same can be done by Right clicking on the project -> properties -> java buid path -> Add External jars.

2. Copy the below web.xml file to the /Struts2Sample/WebContent/WEB-INF/web.xml

Web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Sample</display-name>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
 <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

</web-app>

 

3. Create a model class to store Employee details

package javaonline.sample.struts2.model;

public class Employee {
    private String empCode;
    private String name;
    private String desig;
    private String email;
    private String mobile;
    
 public String getName() {
	return name;
	}
	public void setName(String name) {
  this.name = name;
	}
	public String getDesig() {
  return desig;
	}
	public void setDesig(String desig) {
  this.desig = desig;
	}
	public String getEmail() {
   return email;
	}
	public void setEmail(String email) {
  this.email = email;
	}
	public String getMobile() {
   return mobile;
	}
	public void setMobile(String mobile) {
  this.mobile = mobile;
	}
	public String getEmpCode() {
  return empCode;
	}
	public void setEmpCode(String empCode) {
  this.empCode = empCode;
	}
}

 

4. Create Action Class

 package javaonline.sample.struts2.action;

import org.apache.struts2.interceptor.validation.SkipValidation;

import javaonline.sample.struts2.dao.EmpDAO;
import javaonline.sample.struts2.model.Employee;

import com.opensymphony.xwork2.ActionSupport;
 
public class EmpAction extends ActionSupport {
     
    private static final long serialVersionUID = 1L;
    private Employee empDetail;
     
 
    public Employee getEmpDetail() {
		return empDetail;
     	}


	public void setEmpDetail(Employee empDetail) {
  this.empDetail = empDetail;
  	}


	@Override
	@SkipValidation
    public String execute() throws Exception {
         
      return INPUT;
         
        }
   
    public String getEmployeeDetails() throws Exception {
         
     System.out.println("emp code" + empDetail.getEmpCode());  
     EmpDAO dao=new EmpDAO();
     Employee emp1=dao.GetEmployeeDetail( empDetail.getEmpCode());
     empDetail.setEmpCode(empDetail.getEmpCode());
     empDetail.setName(emp1.getName());
     empDetail.setDesig(emp1.getDesig());
     empDetail.setEmail(emp1.getEmail());
     empDetail.setMobile(emp1.getMobile());
     
        return SUCCESS;
         
    }

	
		
    public void validate(){
		
      System.out.println("In validate");
	     
      if ( empDetail.getEmpCode()==null ||  empDetail.getEmpCode().length() == 0 ){ 
	 
	    addFieldError( "empDetail.empCode", "Please fill Employee Code" );
	         
	    }
	 
	}
   
    }

Note : We have created two methods (execute & getEmployeeDetail) in one action. @SkipValidation indicates that the validate method is skipped for the method execute.

5. Create DAO class for retrieving data based on employee code and capture in Employee model. This is optional.

package javaonline.sample.struts2.dao;

import javaonline.sample.struts2.model.Employee;

public class EmpDAO {

	public Employee GetEmployeeDetail(String code)
	    {
	    //write code to get employee details from database and capture in Employee bean
	    	Employee e1=new Employee();
	    	e1.setEmpCode(code);
	    	e1.setName("Kumar");
	    	e1.setDesig("Software Engineer");
	    	e1.setEmail("abc@xyz.com");
	    	e1.setMobile("2323353232");
	    	return e1;
	    }
	    
}

 

6. Create view pages (i.e jsp pages)

1. Index.jsp
2. GetEmployeeCode.jsp
3. Display.jsp

Each jsp will have the taglib directive at the top of the it <%@ taglib prefix=”s” uri=”/struts-tags” %>.
Index.jsp should look like:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<!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>My First Struts2 Project</title>
</head>
<body>
Welcome to Struts 2 Sample Project. 
 <s:form action="empAction.action">
            <s:submit key="submit" value="Get Employee Details" />
        </s:form>
</body>
</html>

 

code of GetEmployeeCode.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Employee Code</title>
</head>
<body>
<h3>Employee Code Input</h3>
 
    <s:form action="empAction1.action">
      <s:textfield name="empDetail.empCode" label="Enter Employee Code" /> 
    <s:submit/>
       
</s:form> 
</body>
</html>

 

code of Display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Employee Details</title>
</head>
<body>
<h3>Employee Details</h3>
 
<s:form action="empAction1.action">
      <s:label name="empDetail.empCode" label="Employee Id" />
      <s:label name="empDetail.name" label="Name" />
      <s:label name="empDetail.desig" label="Designation" />
      <s:label name="empDetail.email" label="Email" />
      <s:label name="empDetail.mobile" label="mobile" />
 
</s:form> 
</body>
</html>

 

Finally struts.xml

<?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.3.dtd">
 
<struts>
    
  <constant name="struts.devMode" value="true" />
    
  <package name="default" namespace="/" extends="struts-default">
               
    <action name="empAction" class="javaonline.sample.struts2.action.EmpAction">
      <result name="input">/GetEmployeeCode.jsp</result>
    </action>
    <action name="empAction1" class="javaonline.sample.struts2.action.EmpAction" method="getEmployeeDetails">
    	   <result name="input">/GetEmployeeCode.jsp</result>
           <result name="success">/Display.jsp</result>
   </action>
  </package>
</struts>

Now sample strut2 project is completed. Yuo can run the project by invoking http://localhost:8080/Struts2Sample/Index.jsp

index page input pagevalidationdisplay

Leave a Reply