08 - First Hello World! Application in Struts

Introduction:

  • As you know the structure of Struts applications, let us create our first web application.

  • There are no inputs required from user. This application will simply print a greeting message to user.

Requirements are:

     Please refer to -

     Chapter 06 - Struts Installation   (If Struts is not already installed)

     Chapter 07 - Steps for creating Struts 2 Application for basic requirements

Hello World Application:

 Steps for creating Hello World Application:

  • Our area of concern is : (rest all can be deleted from the previous step based on chapter 7)

    • Web Application 1

      • Web Pages

        • Meta – INF

          • Context.xml

        • Web – INF

          • Web.xml

      • Source Packages

        • Default package

      • Libraries

        • All struts libraries

      • Configuration Files

        • MANIFEST.MF

        • Context.xml

        • Web-fragment.xml

        • Web.xml

  • Now the web application is empty and will run nothing. So to begin from scratch, let us create a folder named “jsp” inside web pages folder. We have to now create “main.jsp” by selecting new java server pages document.

  • As the page is JSP (that is Java Server Page = HTML+ Java), we can embed HTML code in JSP page.  

  • The requirement here is of a Label to display message: “Hello World!”

  • Thus the HTML code will be:

// main.jsp
        <form action = "click" method = "post" name = “form1”>
            < input type = “submit”  value="Click Here" name = “submit” />
        <form>
  • The same form can be created by using struts tags instead of HTML tags.
  • To enable struts tag here, we must include a library with all struts tags. That is “/struts-tags” library is to be added at the top of jsp page. We should set a prefix for this library so that the tags are easily recognizable. The syntax is:                                                                                                                                                                                                                                                                                                                                                               <%@taglib  prefix = "s" uri = "/struts-tags" %>
  • Here, the prefix suggests that from now onwards, in current page the struts tags will be prefixed by “s”. Prefix can be kept as per your choice. But the same prefix will be used throughout the web page for accessing the struts tags elements and attributes.
  • As per our requirement we need a button and a form which encapsulates the button.
  • So the main.jsp can be coded as follows:
// index.jsp
<%-- 
    This is a comment in JSP (multiline). Normally used to print general information about the document. 
    Document   : main
    Created on : Nov 18, 2014, 8:07:51 PM
    Author     : Infinity
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>Hello World Application</title>
    </head>
    <body>
        <s:form action = "click" method = "post" name = “form1”>
        <s:submit value="submit" name = “Click Here” />
        </s:form>              
    </body>
</html>

 

Figure: First run of web page – main.jsp.

  • After running this jsp, following output can be seen:
  • On button click, the page is transferred to “click” action page which is still unavailable. So the output will be.

  Figure: Resource missing error

  • So now we need a result page which displays the required results after button click. So create another jsp page named as “next.jsp” inside jsp folder.
  • Add the following statement to the next.jsp page for displaying required message.

          <h1> <s:property value = “message”/> </h1>

  • s:property> tag is used to access the form field names from form elements using value attribute. Make sure that the value for “value” attribute is same as the name of form element you want to fetch.
  • So the next.jsp looks like:
// result.jsp
<%-- 
    Document   : result
    Created on : Nov 18, 2014, 8:10:02 PM
    Author     : Infinity
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib  prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>Hello World Application</title>
    </head>
    <body>
        <h1>
             
              <s:property value = "message"/> 
           
        </h1>
    </body>
</html>
  • Now to create action pages, create a folder named “action_classes” inside source packages. The folder here is known as package.
  • Create action class “main_class.java” inside “action_classes” package. To make the java class support Actions in Struts, we should always extend it with base class “ActionSupport.java” which is residing under xwork package.
  • This action class resembles Java Beans class wherein, support for getter and setter methods for all the input variables must be provided.
  • The only variable here is variable “message”. So the getter setter methods are as follows:
public void setMessage(String message)
    {
        this.message = message;
    }
    public String getMessage()
    {
        return message;
    }
  • Now, on button click this class will be executed. We need one more method that returns a string of “success” after the action class is executed successfully.
  • That method is execute().  The “success” string is pre-declared in the properties of Struts actions. This resembles returning true or false based in successful run of action class. 
public String execute ()
{
     return “success”;
}
  • So the main_class.java file will be as follows:
//main_class.java
package actions;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author Infinity
 */

public class main_class extends ActionSupport{

   private String message;
   public void setMessage(String message)
                 {
                       this.message = message;
                 }
                public String getMessage()
                 {
                      return message;
    }
    public String execute()
    {
        return "success";
    }
}
  • The last thing left is to co-ordinate the action classes with the JSP pages. This can be done by creating struts.xml file. This is also known as configuration file of Struts 2 Framework. The file consists of mapping of actions to respected JSP pages. What should be executed when is specified in here. The file contains mapping inside <struts> tags as follows:
<struts>

   <package name = "default" extends = "struts-default">

    <action name = "Name of action as per action attribute in form tag" class = “class to be executed on this action, on button click”  method = "method to be executed of the class specified">
        <result name = "success">path of page to be displayed on success event(FQN)</result>
        <result name = "failure"> path of page to be displayed on failure event </result>
        </action>
    </package>
</struts>
  • In our example, struts.xml can written as:

  

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

<struts>
    <!-- Configuration for the default package. -->
     <package name = "default" extends = "struts-default">
        <action name = "click" class = "action_classes.main_class" method = "execute">
            <result name = "success">jsp/next.jsp</result>           
        </action>
    </package>
</struts>
  • Just like our struts.xml file, we also have web.xml file (inside Web – INF folder) which is responsible mainly for session configuration, start-up file configuration, server settings etc.
  • In web.xml, change the welcome file (inside welcome file list tag) to our index.jsp. After corrections, web.xml should look like:
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app version = "3.1" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <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>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file> jsp/main.jsp </welcome-file>
    </welcome-file-list>
</web-app>
  • Running the application will show following page:

    Figure : first successful run of application

  • When user clicks “click here” button, the action page is executed which results in success and from the <result> tag, the value for success is executed. That is, the next  page is displayed. As we don’t have any failure event, only success is returned.   
  • The value of “message” variable is retrieved using <s:property> tag using value attribute.

Figure : Output of Hello World Application.

Like us on Facebook