Saturday 22 November 2014

First struts2 Application


I am going to explain simple struts2 application. Don’t worry if you don’t understand, but follow the steps and try to run the application. You can get full picture of struts2 in subsequent posts.

let’s say there is a simple form which takes a number from user, and displays success message if it is even number, else failure message



I am going to explain it using NetBeans IDE

Step 1 : First create a web project in NetBeans



I just gave the project name as ‘struts2sample’. Press Next
I configured glassfish as my server and press next.


Step 2: You have to setup the necessary jars into your class path. You can download the jar files from “http://struts.apache.org/release/2.3.x/ “. Not all jar files required to run simple Application. Below are the jar files I set in class path.

asm-3.3.jar,
asm-commons-3.3.jar,
asm-tree-3.3.jar,
commons-fileupload-1.3.1.jar,
commons-io-2.2.jar,
commons-lang3-3.1.jar,
freemarker-2.3.19.jar,
javassist-3.11.0.GA.jar,
ognl-3.0.6.jar,
struts-2.3.16.3-lib,
struts2-core-2.3.16.3.jar,
xwork-core-2.3.16.3.jar

Step 3: First create a simple html page, which takes a number as input, and submit the form to server for processing.
numCheck.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Simple struts2 Application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
      <form method="post" action="numberCheck">
          Enter a Number<input type="text" name="number" /><br />
          <input type="submit" value="submit" />
      </form>
  </body>
</html>



You can observe the structure of the application in the above figure.


Step 4: In struts2 environment, we have to handover the requests to struts2. We do this by configuring web.xml.

Fig :Struts Environment

web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>Struts2 Demo App</display-name>
    <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>
    </filter-mapping>
</web-app>

As you observe web.xml, we are forwarding all the requests to struts2 environment by using filter mapping. So now it is struts2 responsibility to process this request.

Step 5: In struts2, a request is handled by action classes. These are acts a model in MVC design pattern. We create an Action class ‘NumberCheckAction.java’, which checks whether given number, is even or not.  Observe the figure ‘Struts Environment’, request is going through the interceptors. These are responsible to set the input parameters. For example in ‘numCheck.html’ we given name ‘number’ to the text box.

Enter a Number<input type="text" name="number" /><br />

Interceptor process this name and update the respective fields in action class. We must provide same property like ‘number’ in action class and provide getter and setter methods.

Request is handled by the execute method of action class. This method returns a string value. Based on the value return by this method, controller ‘struts.xml’ displays particular page. The property ‘number’ set by the interceptors before calling the execute method.

public class NumberCheckAction {
    private int number;
    private static String SUCCESS = "success";
    private static String FAILURE = "failure";

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String execute(){
        if(getNumber() %2 == 0){
            return SUCCESS;
        }
        else{
            return FAILURE;
        }
    }
}


Step 6: Create xml file and name it as struts.xml. struts.xml is the configuration file related to struts2. Make sure the configuration file is available in class path. ‘struts.xml’ contains all the mappings and it acts as a controller in MVC design pattern.

struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="numberCheck" class="NumberCheckAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>
    </package>
</struts>

In struct.xml, we are mapping the action ‘numberCheck’ to class ‘NumberCheckAction’. So when you click the submit button of numberCheck.html page, the request goes to the action class ‘NumberCheckAction’ and execute the ‘execute’ method. If execute method returns the string “success” then success.jsp will display on the browser. If execute method returns “false” then failure.jsp’ is displayed on the browser.

Step 7: Create ‘success.jsp’ and ‘failure.jsp’ files.
success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>Success Page</title>
    </head>
    <body>
        <h1>Hurray, you entered even number</h1>
    </body>
</html>


failure.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>Failure page</title>
    </head>
    <body>
        <h1>Sorry dude, you entered odd number</h1>
    </body>
</html>

The total structure looks like below.




It is time to run the application, Run ‘numCheck.html’ .

When you enter an even number and submit the form, it displays ‘success.jsp’ file.



When you enter an odd number and submit the form, it displays ‘failure.jsp’ file.
 






How struts works?
Struts provides a filter dispatcher ‘org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter’  to handle all the request that comes to struts. You just forward all the request to this dispatcher using below configuration in web.xml.


<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>
</filter-mapping>

Once request reaches to filter dispatcher, interceptors instantiate the action object with request parameters. The property ‘number’ for the action object of class ‘NumberCheckAction’ is set by interceptors.

Once the action object properties populated, execute method of this object will be executed. This method returns a string value, based on the returned value of execute method, struts controller displays the result.

For example
<package name="default" extends="struts-default">
        <action name="numberCheck" class="NumberCheckAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>
</package>

If action method returns string “success”, then success.jsp is displayed.
If action method returns string “failure”, then failure.jsp is displayed.

You can specify other action method than execute. If you don’t specfy action method name explicitly, then struts assume ‘execute’ method as action method by default.

<action name="numberCheck" class="NumberCheckAction" method=”feedback”>

In the above action, feedback is the action method to execute.
 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment