10A - Program to create a calculator in Struts Part 1

Introduction:

  • Coding applications in Struts 2 is very easy. So now let us create a calculator based application.  
  • The number of inputs required from user is: two numbers and the output is the result of addition, subtraction, multiplication, modulo, etc. We can also design a scientific calculator wherein secant, cosecant, tangent and other functionalities can be implemented. This can be done by using the Math class in java.lang package.

Requirements are:

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

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

Calculator Application: 

  • 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 source packages folder. And the path to find these and connect these pages is 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 “first.jsp” by selecting new Java server page 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, a textfield to retrieve the number and a submit button to process the form. Thus the HTML code will be:
// index.jsp
        <form action = "click" method = "post" name = “form1”>
           <label value = "Enter number 1 : " name = “l1” />
           <input type = “text” name = "x"/>
           <label value="Enter number 2 : " name = “l2” />
           <input type = “text”  name="y"/>
           < input type = “submit”  value="click" 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”. A 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 label, button and a form which encapsulates these elements.
  • So the index.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   : index
    Created on : Oct 31, 2014, 4:17:20 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>Calculator Application</title>
    </head>
    <body>
        <s:form action = "click" method = "post" name = “form1”>
        <s:label value = "Enter number 1 : " name = “l1” />
        <s:textfield name = "x"/>
        <s:label value="Enter number 2 : " name = “l2” />
        <s:textfield name="y"/>
        <s:submit value="submit" name = “submit” />
        </s:form>
               
    </body>
</html>
  • After running this jsp, following output can be seen:

Figure - Calculator program output

  • On button click, the page is transferred to “click” action page which is still unavailable.
  • We also need a result page which displays the required results 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 Math properties:

    The addition of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans1"/>

     The subtraction of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans2"/>

     The multiplication of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans3"/>

  • So the result.jsp looks like:
// result.jsp
<%-- 
    Document   : result
    Created on : Nov 3, 2014, 10:11: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>Calculator Application</title>
    </head>
    <body>
        <h1>
            
  The addition of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans1"/> 
  <br>
  The subtraction of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans2"/>
  <br>
  The multiplication of <s:property value = "x"/> and <s:property value = "y"/> is : <s:property value = "ans3"/>
            
        </h1>
    </body>
</html>
  • Now to create action pages, create a folder named actions inside source packages. The folder here is known as package.
  • Create action class “calc” inside “actions” package as seen in previous tutorials.
  • 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 variables here are variable “x” and variable “y” (check the name attribute of text field in our form). So the getter setter methods are as follows:
public void setX(int x)
    {
        this.x = x;
    }
    public int getX()
    {
        return x;
    }
    
    public void setY(int y)
    {
        this.y = y;
    }
    public int getY()
    {
        return y;
    }
  • 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 calculate().  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 calculate ()
{

   // our code for calculator
     return “success”;
}
  • So the check java file will be as follows:
//calc.java
package actions;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author Infinity
 */
public class calc extends ActionSupport{
  
    private int x,y, ans1, ans2, ans3;
    public void setX(int x)
    {
        this.x = x;
    }
    public int getX()
    {
        return x;
    }
    
    public void setY(int y)
    {
        this.y = y;
    }
    public int getY()
    {
        return y;
    }

    public void setAns1(int ans1)
    {
        this.ans1 = ans1;
    }
    public int getAns1()
    {
        return ans1;
    }
    public void setAns2(int ans2)
    {
        this.ans2 = ans2;
    }
    public int getAns2()
    {
        return ans2;
    }
    public void setAns3(int ans3)
    {
        this.ans3 = ans3;
    }
    public int getAns3()
    {
        return ans3;
    }
    public String calculate()
    {

      ans1 = x + y;
      ans2 = x - y;
      ans3 = x * y;
      return "success";
    }
}
  • You can also create scientific calculator. So, check.java can be also coded as follows:
// calc.java

package actions;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author Infinity
 */
public class calc extends ActionSupport{

    private int x, y;
    private double ans1, ans2, ans3;

    public void setX(int x)
    {
        this.x = x;
    }
    public int getX()
    {
        return x;
    }
    public void setY(int y)
    {
        this.y = y;
    }
    public int getY()
    {
        return y;
    }
   public void setAns1(double ans1)
    {
        this.ans1 = ans1;
    }
    public double getAns1()
    {
        return ans1;
    }
    public void setAns2(double ans2)
    {
        this.ans2 = ans2;
    }
    public double getAns2()
    {
        return ans2;
    }
    
    public void setAns3(int ans3)
    {
        this.ans3 = ans3;
    }
    public double getAns3()
    {
        return ans3;
    }
    public String calculate()
    {
        ans1 = Math.sin((double) x);
        ans2 = Math.cos((double) y);
        ans3 = Math.tan((double) y);

        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 = "actions.calc" method = "calculate">
            <result name = "success">result.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 : first successful run of application

  • Enter two numbers in the text fields and click on the 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. As we don’t have any failure event, only success is returned after calculations.   
  • The numbers are fetched from the first form (index.jsp) stored in a variable called “x” and “y”. The value of this variable is retrieved using <s:property> tag using value attribute.


Figure : enter two numbers (normal calculator)

Figure : enter two numbers (normal calculator)

Figure : Result page (result.jsp)

 

Figure : enter two numbers (Scientific calculator )

Figure : Result page

 

 

Like us on Facebook