09 - Program to print user name on button click in Struts

Introduction:

  • Now that the basic concepts of Struts Framework are clear, let us design our first Struts 2 application that prints a welcome message of “Hello World!” to user with a single button click.
  • Struts 2 application can be coded in two different ways:
    • Without using Struts 2 plugin
    • By using Struts 2 plugin provided by NetBeans IDE.
  • The application created without using Struts 2 plugin becomes a simple MVC application (more like a Struts 1 application) and transformation of that into Struts 2 becomes a tedious.
  • The tools and software’s we will be using are:
    • Installed version of Java 1.7 (i.e. jdk 1.7)
    • Installed version of Java Runtime Environment (i.e. jre 1.7)
    • Installed NetBeans: version above 7.0 (because the versions below 7.0 do not provide much flexibility with Struts 2 Framework).

Requirements:

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

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

Program to print user name on button click:        

  • Here, the required things are : (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
  • All the JSP’s (Java Server Pages), responsible for input – output activities are to be placed in the Web Pages folder. All the actions, that is, what should happen on button click or on dropdown menu click etc. are to be placed in the source packages folder. And the path to find these and connect these pages are to be placed in “configuration files” folder.

Note :

Steps to create Struts Application:

  1. Create JSPs
  2. Create action pages according to JSPs
  3. Connect the JSPs and action pages using configuration files (such as web.xml and struts.xml)
  • Now the web application is empty and will run nothing. So to begin from scratch, let us create a folder named “jsp” inside the web pages folder. And create “index.jsp” by selecting new Java server page document.
  • 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”. A prefix can be kept as per your choice. But the same prefix will be used throughout the web page for accessing the struts tag elements and attributes.
  • As per our requirement, we need a label, button and a form which encapsulates these elements. So to create the web page, following needs to be added inside <body> tag:
  • <S: label value = "Put your name in the text box and click the button" name = "label1"/>: Labels can be placed even without <s:label/> tag.
  • <s:textfield name = "name"/>: Name attribute is a compulsory attribute because it will be used for identification of text field in other forms
  • <s:submit value = "CLICK" name = "submit"/> : value attribute represents the text displayed on the button. Submit button is normally used to submit the values of the current form to the next form. Normal button does not submit the value, but can be used for simple operations to be performed on the same page (that is, not on the next page). And cancel button is used for form cancelling etc. (as per requirement).
  • So the index.jsp can be coded as follows:
// index.jsp

<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib  prefix = "s" uri = "/struts-tags" %>

<html>
   <body>
     <s:form method = "post" action = "hello_action">

         <s:label value = "Put your name in text box and click the button" name = "label1"/>
         <s:textfield name = "name"/>
        <s:submit value = "CLICK" name = "submit"/>
                           
     </s:form>        
   </body>
</html>

 

  • After running this jsp, following output can be seen:

  • On button click, the page is transferred to “hello_action” page which is still unavailable. So following error can be seen:

Figure : Application first run – without specifying the action of button click

  • The page written in action of <s:form> tag can be seen in the URL in above snapshot.
  • We also need a result page which displays the name of the user entered in text field after button click. So create another jsp page named as “result.jsp” inside jsp folder.
  • Add the following statement to the result page for displaying user name :

    Hello <s:property value="name"/>

  • <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 result.jsp looks like:
// result.jsp
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib prefix = "s" uri = "/struts-tags" %>
<html>
<body>
        <h1>Hello <s:property value = "name"/></h1>
</body>
</html>

  • Now to create action pages, create a folder named action_jsp inside source packages. The folder here is known as package. 

Figure : Creating new package for action files

  • Create action class “hello_action” inside “action_jsp” package as follows:

Figure : Creating action file(hello_action.java)

 

Figure : Layout of action file (hello_action.java)

  • 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 input variable here is name (check the name attribute of text field in our form). So the getter setter will be:
public void setName(String name)
{
           this.name = name;
}
public String getName()
{
    return name;
}
  • Now, on button click this class will be executed. We need one more method that returns a string of “success” if the action class is executed successfully. That method can be of any name such as: execute() or calculate() etc. The “success” string is pre-declared in the properties of Struts actions. This resembles returning true or false based on the successful run of action class.
public String execute()
{
     return “success”;
}

 

  • So the hello_action java file will be as follows:
// hello_action.java

package action_jsp;

import com.opensymphony.xwork2.ActionSupport;

// everything in here must be kept public to have package level access.

public class hello_action extends ActionSupport
{
   private String name;
   // getter and setter methods for the form element value

   public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
//method that returns success or failure on action
    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>

[Note : FQN : Fully Qualified Name the class. ]

 

  • 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>

    <package name = "default" extends = "struts-default">
      <action name = "hello_action" class = "action_jsp.hello_action" method = "execute">
        <result name = "success">result.jsp</result>
        <result name = "failure">index.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/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • Running the application will show following page:

Figure - Output from the program run

  • Enter user name in text field and click on button. The action page is executed which results in success and from the <result> tag, the value for success is executed. That is, the result page is displayed.
  • The user name is fetched from the first form (index.jsp) stored in a variable called “name”. The value of this variable is retrieved using <s:property> tag using value attribute.

Figure - Hello user

 

Like us on Facebook