10B - Program to create a calculator Part 2

Introduction:

  • We have already created simple calculator as well as a scientific calculator. But as you can see, there is only one submit button and on click of submit button, it displays all the mathematical operations.
  • But the actual working of the calculator is different. As per user’s choice, the answer should be displayed.
  • The applications can have more than one submit buttons in a single form. This is an additional feature of Struts 2.x. The feature is extended in this framework, but it was not present in Struts 1.x. The feature is known as Dynamic Action (based on the concept of Dynamic Method Dispatch in core Java).

Dynamic Method Dispatch:

  • The Dynamic Method Dispatch is a property of object oriented languages like Java, .Net, C# etc.
  • The property states that, when inheritance and overridden methods are used in a program, which version of method (that is, body of which method) will be executed is determined at run time and not at compile time. Based on what the current reference variable is referring to, the overridden methods are differentiated and executed.
  • In our application, on click of add button, addition operation should be carried out, on click of sub button, subtraction operation should be carried out and so on and so forth.
  • But the form remains same. That is the action of the form is defined only once. To achieve this, let’s check out the below example.

Calculator Application:

// index.jsp
<%-- 
    Document   : index
    Created on : Nov 7, 2014, 11:11:29 AM
    Author     : Admin
--%>

<%@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">
            
            <s:label value = "Number 1"/>
            <s:textfield name = "x"/>
            <s:label value = "Number 2"/>
            <s:textfield name = "y"/>
            <s:label value = "Result"/>
            <s:textfield name = "result"/>
            <s:label value = "Called Method is:"/>
            <s:textfield name = "methodname"/>
            <s:submit/>
            <s:submit action = "addNumber" value = "ADD"/>
            <s:submit action = "subNumber" value = "SUB"/>
            <s:submit action = "divNumber" value = "DIV"/>
            <s:submit action = "mulNumber" value = "MUL"/>                               
        </s:form>        
    </body>
</html>

 

//struts.xml

<!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.enable.DynamicMethodInvocation" value = "true"/>

    <package name = "default" extends = "struts-default">
<!--
       <action name = "click" class = "jsp_actions.calc" >
         <result name = "success">index.jsp</result>
      </action> 
    -->
      <action name = "addNumber" class = "jsp_actions.calc" method = "add">
         <result name = "success">index.jsp</result>
      </action>

      <action name = "subNumber" class = "jsp_actions.calc" method = "sub"        
        <result name = "success">index.jsp</result>
      </action>

      <action name = "divNumber" class = "jsp_actions.calc" method = "div">
         <result name = "success">index.jsp</result>
      </action>

      <action name = "mulNumber" class = "jsp_actions.calc" method = "mul">
         <result name = "success">index.jsp</result>
      </action>
   </package>
</struts>

 

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

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jsp_actions;

import com.opensymphony.xwork2.ActionSupport;

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

    private double result, x, y;
    private String methodname;

    public String execute() 
    {
    result = 1;
    setMethodname("execute");
    return SUCCESS;
    }

    public String add()
    {
        result = x + y;
        setMethodname("add");
        return SUCCESS;
    }
    public String sub()
    {
        result = x - y;
        setMethodname("sub");
        return SUCCESS;
    }
    public String mul()
    {
        result = x * y;
        setMethodname("mul");
        return SUCCESS;
    }
    public String div()
    {
        setMethodname("div");

         if (y != 0)
        {
        result = x / y;
        }
         else if (x != 0)
        {
            result = y / x;
        }
        else
        {
            result = 0.0;
        }
            
        return SUCCESS;
    }
    
    public double getX()
    {
        return x;
    }
    public double getY()
    {
        return y;
    }
   
    public void setX (double x)
    {
        this.x = x;
    }
 
    public void setY (double y)
    {
        this.y = y;
    }

    public void setResult (double result)
    {
        this.result = result;
    }

    public double getResult()
    {
        return result;
    }
    public void setMethodname (String methodname)
    {
        this.methodname = methodname;
        
    }
    public String getMethodname()
    {
        return methodname;
    }
}

Explanation:

  • The main thing to concentrate upon is

<s:submit action = "addNumber" value = "ADD"/>

<s:submit action = "subNumber" value = "SUB"/>

<s:submit action = "divNumber" value = "DIV"/>

<s:submit action = "mulNumber" value = "MUL"/>       

  • Here, we can define actions for all individual buttons. These buttons are simple submit buttons only but having different actions each. That is, when the button labeled as “ADD” is clicked, the action to be executed is addNumber, when the button labeled as “DIV” is clicked; the action to be executed is divNumber and so on.
  • Although you can verify the main action of page, that is <s:form action=”click”> remains as it is.

How Mapping is done?

  • This can be explained by following code from struts.xml file:

        <action name = "addNumber" class = "jsp_actions.calc" method = "add">

                        <result name = "success">index.jsp</result>

        </action>

       <action name = "subNumber" class = "jsp_actions.calc" method = "sub">

                        <result name = "success">index.jsp</result>

        </action>

 

  • Here, when ADD button is clicked, the action is mapped accordingly. That is, the action name “addNumber” is followed. Which has the method add() in action class (calc.java).
  • The control is transferred to add() method of action class, addition is performed and SUCCESS is returned. So here, result with name success is followed, which shows index.jsp with the returned values.
  • The same is followed for SUB button. That is, the program control finds the name of action specified in the <s:submit> tag and follows this action method from the action classes accordingly.
  • We can also specify the failure result for DIVISION method, wherein, the division method should return failure event in case if any of the number is zero. This can be done as follows:
public String div()
    {

      setMethodname("div");
      if (y == 0)
        {
        result = 0.0;
        return FAILURE;
        }
        else if (x == 0)
        {
            result = 0.0;
            return FAILURE;
        }
        else
        {
            result = x / y;
            return SUCCESS;
         }
   }

 

  • Running the application shows following output:

Figure : Addition Action

Figure : Addition Action

Figure : Divide Action

Figure : Divide Action

Figure : Subtraction Action

 

 

 

 

 

 

 

 

 

 

 

 

Figure : Subtraction Action

 

Figure : Multiplication Action

  • Verify the action name called in the URL. For addition action, URL shows addNumber.action. For subtraction action, URL will show subNumber.action and so on an so forth.

Like us on Facebook