Skip to main content

Creating a Struts-2 hello world application on eclipse

Hi,

This is a getting started tutorial for struts-2. Struts-2 is similar to struts-1 but there are certain changes in terms of functionality and syntax.
The main components needed to create the demo application are as follows:
1. Eclipse indigo.
2. Struts-2 distribution:- To download struts-2 distribution go to 'http://struts.apache.org/download.cgi#struts238-SNAPSHOT' and download 'Full Distribution:struts-2.3.7-all.zip (76mb) [PGP] [MD5] '
3. Tomcat 7.

That is all you need to create a struts application.

Application Structure: The demo application that we are going to create using struts-2 is a login application. The application will be having following components:
1. index.jsp
2. HelloWorld.jsp
3. error.jsp
4. HelloWorldAction.java

Now the application proceeds as follows:
1. When the application starts the user is presented with 'index.jsp' where the user enters username and password.
2. On submitting the 'index.jsp' page the request is directed to Action class which in our case is 'HelloWorldAction.java'.
3. 'HelloWorldAction.java' checks whether login data is valid or not. If login is valid then user is directed to 'HelloWorld.jsp' page else user is directed to 'error.jsp' page.


Getting Started:
With above grounds we will now start creating our application.

Steps:
1. Unzip the struts-2 binary that you downloaded above. You will get following files in the 'lib' folder of unzipped distribution (nearly 84 files will be there):

2. Create a dynamic web project in Eclipse J2EE Indigo.
3. Select following jar files from the unzipped distribution and paste them in the 'WebContent-> WEB-INF->lib' folder:
     a. asm-3.3.jar
     b. asm-commons-3.3.jar
     c. asm-tree-3.3.jar
     d. commons-fileupload-1.2.2.jar
     e. commons-io-2.0.1.jar
     f. commons-lang3-3.1.jar
     g. freemarker-2.3.19.jar
     h. javassist-3.11.0.GA.jar
     i. ognl-3.0.5.jar
     j. struts2-core-2.3.4.1.jar
     k. xwork-core-2.3.4.1.jar
4. The structure of your project will look like:

5. Notice all the files present under 'lib' folder.
6. Add three JSP files 'index.jsp', 'HelloWorld.jsp' and 'error.jsp' under the 'WebContent' folder.
7. Now create a package under src and name it 'rajeev.struts2.action'.
8. Add out action class 'HelloWorldAction.java' under the package 'rajeev.struts2.action' created above.
9. Add an XML file 'struts.xml' under the src folder.
10. The final project structure will look like:


We are done with adding the components to the project in eclipse. Now we need to add necessary code to these components.

Code Listings:
 Now we will be adding code to various components.

1. Action: Firstly we will be adding code to out action class which is 'HelloWorldAction.java'. Add following code:

package rajeev.struts2.action;

public class HelloWorldAction {

    private String name;
    private String pass;

       public String execute1() throws Exception {
           String result=null;
           if(name.equals("rajeev")  && pass.equals("password"))
           {
                   result="success";
           }
           else
           {
                  result="fail";
           }
          return result;
       }
      
       public String getName() {
          return name;
       }

       public void setName(String name) {
          this.name = name;
       }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }
}

The action class is a simple class that doesn't extends any other class. It has two string parameters to hold the User Name and Password given by the user and a method 'execute1()' that holds the logic to check whether the login is valid or not.

2. web.xml: Following code snipped is needed to be added to web.xml of your web application:
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>struts</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <filter>
    <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>

The code highlighted in yellow is the extra code that tells your web application that it is using struts2.


3. struts.xml: Next we need to update 'struts.xml' with following 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>
<constant name="struts.devMode" value="true" />
   <package name="default" extends="struts-default">
    
      <action name="hello"
            class="rajeev.struts2.action.HelloWorldAction"
            method="execute1" >
            <result name="success">/HelloWorld.jsp</result>
            <result name="fail">/error.jsp</result>
      </action>
   </package>
</struts>
Here the lines highlighted in yellow specify the action declaration rest is struts specific code. Now in the <action> tag we have following attributes with following meaning:
      a. name    // specifies the name with which the action will be accessed.
      b. class    // specifies the class that will act as action.
      c. method   // specifies the method that must be executed when the action executes.
next we have two <result> tags. These tags define which view will be displayed depending on the value returned from the 'execute1()' method of the action. If 'execute1()' returns "success" then 'HelloWorld.jsp' page will be displayed, if 'execute1()' method of the action returns "fail" then 'error.jsp' page will be displayed.

4. View(jsp files): now we need to add these code segments to the three jsp files:

    index.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>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello" method="post">     
      User Name: <input type="text" name="name"/> <br>
      Password: <input type="text" name="pass" /><br>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>
Here the 'action' attribute tells to which action class the request should be directed. In our case the request will be directed to 'hello' action that maps to 'rajeev.struts2.action.HelloWorldAction' in struts.xml above. Here the 'name' attribute of the HTML form will be automatically mapped to the 'name' attribute of 'HelloWorldAction.java' and 'pass' attribute of the HTML form will be automatically mapped with the 'pass' attribute of 'HelloWorldAction.java'.

HelloWorld.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h2>HelloWorld.jsp</h2><br><br>
   Hello World, <s:property value="name"/>
</body>
</html>
Here the highlighted segment is the code related to struts-2 rest is HTML. Here the 'value' attribute will be mapped to the 'name' attribute of the 'HelloWorldAction.java'.

error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>
<h2>HelloWorld.jsp</h2><br><br>
Error in login.
</body>
</html>
This jsp file is a simple HTML file with no struts-2 specific code.

Execution:
Now we are done with configuring and creating our application. To execute the application right click on the project in the Project Explorer in eclipse and run as 'Run On Server', after the server starts running you will be displayed with index.jsp file.
if you enter correct User Name and Password then you will get 'HelloWorld.jsp' page:


However if the credentials entered are wrong then 'error.jsp' page will be displayed:

I hope this tutorial will help as a start up tutorial for struts-2 application.
Feel free to submit your queries and suggestions.

Thanks.

Comments

  1. Hi,

    I tried to re-execute the code. However this time I am using Eclipse Kepler and Struts2 version 2.3.16.3. I am able to successfully run the index.jsp, HelloWorld.jsp and error.jsp. Kindly give the steps where you are facing the problem.

    Also as per the error log shared it seems there is some problem with the action. Try re-checking the location and contents of your struts.xml file and the value of 'action' form attribute in index.jsp.

    Regards
    Rajeev

    ReplyDelete

Post a Comment

Popular posts from this blog

Uploading a binary file to RESTful web service in java using Jersey

Hi, Recently I had a situation where I was supposed to upload a binary file to a server side RESTful web service created in Jersey. I faced a lot of trouble in doing so because always one or the other part of the hood was not working properly. The following post gives a step by step process as how to create a RESTful service that accepts uploaded binary files. Pre-requisites: 1. A running RESTful service based on Jersey. 2. An HTML page with file upload component. 3. Tomcat 7 as web server. 4. Eclipse indigo. Note: Let us suppose that tomcat is running on same machine on which the HTML client is present. So we will be using the base domain URL as ' http://localhost:8080/ '. If your service and client are located on different instances of tomcat then replace the localhost part of the URL with the IP address of the machine on which the REST service is running. Step 1 (Eclipse setup): a. Create a 'Dynamic Web Project' in eclipse indigo. Let us say that thi

Using R Programming Language inside Java

Hi, This tutorial walks you through using R programming language inside a java program. R is a powerful programming language for Machine Learning and Data Mining. It contains implementation of various Machine Learning algorithms. Recently i had a situation where i was supposed to use these machine learning algorithms inside my java program. I searched the web but the stuff i found was not of much help. Thus i thought of putting the same in the form of this tutorial. This tutorial is not intended to teach you R language. It is only to help you integrate R to Java and then to use R functions inside a Java program. Pre-requisite: Following things are needed to be pre-configured on your system to use R in Java program: 1. R workbench:  R has got a console known as RGui where R commands/programs could be executed. To install RGui simply go to  http://cran.r-project.org/bin/windows/base/  and download the ' Download R 3.0.2 for Windows   (52 megabytes, 32/64 bit) '. Simply

Creating a JAX-WS Web Service and Client using Eclipse Indigo

Creating a JAX-WS Web Service and corresponding client is a very trivial task. However I faced various problems while doing the same mainly while creating a client for the web service. This was mainly because the contents I found on the Internet were in a distributed manner. So I thought of creating a tutorial which binds all the concepts at one place. So this tutorial does not teaches indepth concepts of web services. Instead it guides as how to create a Web Service and a seperate client. Software Requirements: 1. Eclipse Indigo. Note: To download Eclipse Indigo follow the link http://www.eclipse.org/downloads/. Then select 'Eclipse IDE for Java EE Developers'. Process: We will proceed with the creation of web service and client in following two steps: 1. Creating Web Service 2. Creating client to consume web service. 1. Creating Web Service: Creating of a JAX-WS web service is not a very tough task. We simply create a class(normal Java class) and define certai