Basic arithmetics

Ok, (hopefully) everybody knows about the basic arithmetic operations: Add, subtract, multiply and divide. To do this it needs two number,   one of the four operators and the computer spits out the result. A trivial task, you probably can solve by head. But why perform this effort? Let this do our computer so that we can use this in the browser.

In this part of the tutorial, you learn about server side processing using a so called   managed bean.

Either create a new web project, as described in “The first Web application”, with the difference that you name this project “TinyCalulator” or just rename the existing project. For the latter, in the project view click with the secondary (usually right) mouse button on the project “JSFTutorial” and select from the popup menu “Rename…”. It appears a small dialog for the renaming of the project:

As new name,please choose “TinyCalculator” and tick “Also Rename Project Folder”, to rename the folder in conformity.

Ok, what do you need for this new project? There we have two input fields, four buttons for the operations and one field for the result. Go to index.html and edit the source.

The figure shows this task in the context of NetBeans. Further on, I ommit such figures. Instead of that, you’ll find source code listed. You may copy and paste the text, but for better training effect you should edit it by yourself.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Tiny calculator</title>
    </h:head>
    <h:body>
        <h1>Tiny calculator</h1>
        <h:form>
            <h:outputLabel value="Param 1:"/>
            <h:inputText id="param1"/>
            <br/>
            <h:outputLabel value="Param 2:"/>
            <h:inputText id="param2"/>
            <br/>
            <h:commandButton value="add"/>
            <h:commandButton value="substract"/>
            <h:commandButton value="multiply"/>
            <h:commandButton value="divide"/>
            <br/>
            <h:outputLabel value="Result:"/>
            <h:outputText id="result"/>
        </h:form>
    </h:body>
</html>

As you may have recognized, we now have some labels and all the components described earlier. So far, ther is no calculation yet. Please start this application.

In both input fields you may enter values. If you click onto a button nothing seems to happen. Nothing? If you observe precisly, you’ll figure out the page being reloaded.

Let’s take a closer look to the page’s (HTML) source code (formatted a pretty nicer).

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Tiny calculator</title>
  </head>
  <body>
    <h1>Tiny calculator</h1>
    <form id="j_idt8" name="j_idt8" method="post"
            action="/TinyCalculator/index.xhtml"
            enctype="application/x-www-form-urlencoded">
      <input type="hidden" name="j_idt8" value="j_idt8" />
      <label>Param 1:</label>
      <input id="j_idt8:param1" type="text" name="j_idt8:param1" />
      <br />
      <label>Param 2:</label>
      <input id="j_idt8:param2" type="text" name="j_idt8:param2" />
      <br />
      <input type="submit" name="j_idt8:j_idt13" value="add" />
      <input type="submit" name="j_idt8:j_idt14" value="substract" />
      <input type="submit" name="j_idt8:j_idt15" value="multiply" />
      <input type="submit" name="j_idt8:j_idt16" value="divide" />
      <br />
      <label>Result:</label>
      <span id="j_idt8:result"></span>
      <input type="hidden" name="javax.faces.ViewState"
            id="javax.faces.ViewState"
            value="3061588258500397437:-7913731195929753954"
            autocomplete="off" />
    </form>
  </body>
</html>

A few more things happened than in the first web app. Time, to take a particulary look onto what has been changed by the server.

Our original source

<h:head>
   <title>Tiny calculator</title>
</h:head>

reaches the browser as

<head>
    <title>Tiny calculator</title>
</head>

This is the same as in the first app. What will happen, if you ommit this prefix “h:”? In this tiny app it will be the same! As you’ll learn later on, there are some components which belong to the header and which need this prefix (it addresses head out of th namepace which is definde by h:). And without this namespace, JSF cannot handle this. Thus, allways use this namespace whethr you need it or not in your JSF app. It’ll be there, when you need it. Same applies to the body.

Much more happens on “h:form”

<h:form>
    [...]
</h:form>

It’s getting bloated up in the browser.

<form id="j_idt8" name="j_idt8" method="post"
        action="/TinyCalculator/index.xhtml"
        enctype="application/x-www-form-urlencoded">
  <input type="hidden" name="j_idt8" value="j_idt8" />
[...]
  <input type="hidden" name="javax.faces.ViewState"
        id="javax.faces.ViewState"
        value="3061588258500397437:-7913731195929753954"
        autocomplete="off" />
</form>

There you have an id. You may choose it by your self, resulting in a much better name. This id must be unique within a page and is used to address a component in the component tree, e.g. on server side

Also interesting are two hidden fields, which JSF uses to carry some additional information. JSF needs to intermediate persist the components state. According to configuration, this might be done on server or client side. The value of the hidden field with id “javax.faces.ViewState” is an identifier to store the state on server side. It changes on every call. If you choose client side to store the state, this value might contain much more information, depending on the size of the form. You’ll find more information on state later on in this tutorial, when dealing with JSF lifecycle and configuration.

Let’s get further on fast: An outputLabel will be translated into (html) label übersetzt, an inputText into   input type “text”, a commandButton in input type “submit” and the outputText will be transformed into a span. In this application. Depending on the context, some components may be transposed a bit different. All these tags are abstractions of   HTML elementss. And every components gets its own unique id ore a name according to th nesting.

A lot of stuff so far and the application still cannot calculate. Luckily, the page’s source is a little. And it will not grow much: The calulation mustn’t be part of the page. It has to be done on server side. But where?

This is where coffee bean JavaBean comes into play. A JavaBean follows convention to access attributes via getters and setters (two Methods named like setAtrribute and   getAttribute).

Pleas create a new class of “JSF Managed Bean”.

As class name use “CalculatorBean”. Further down in the form you’ll find it again as name, with lower char starting.

For “Package” choose an appropriate name. e.g.”calculator”. An interesting configuration may be done at “Scope”. With this, you’ll decide whether this bean will be used as an object for a single request, a session or the whole application. Just keep “request” and finish the wizard by [Finish]. NetBeans now creates a new class and some entries in the configuraion files. Alternativly you can create a pure Java class and edit the configuration manually. A praise to the wizzard. 😉

Complete the source as this:

package calculator;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

/**
 *
 * @author mmueller
 */
@ManagedBean
@RequestScoped
public class CalculatorBean {
    private int _param1;
    private int _param2;
    private String _result;

    public CalculatorBean() {
    }

    //
    public int getParam1() {
        return _param1;
    }

    public void setParam1(int param1) {
        _param1 = param1;
    }

    public int getParam2() {
        return _param2;
    }

    public void setParam2(int param2) {
        _param2 = param2;
    }

    public String getResult() {
        return _result;
    }
    // 

    public String add(){
        _result = Integer.toString(_param1 + _param2);
        return "";
    }

    public String substract(){
        _result = Integer.toString(_param1 - _param2);
        return "";
    }

    public String multiply(){
        _result = Integer.toString(_param1 * _param2);
        return "";
    }

    public String divide(){
        _result = _param2 == 0 ? "n/a" : Double.toString(_param1 / (double)_param2);
        return "";
    }

}

Two attributes refer to our two parameters and the third is used for the result. This result will be calculated by four methods which are named as each of the basic arithmetics and stored in this attribute. This looks strange. Usually you would pass over the result as return value of the method. In this application the return value will be an empty string (or might be null if you prefer this). And you may have recognized the annotations (@ManagedBean, @RequestScope) which refer to your input in the wizzard. Be a bit patient to see what this is for.First you should write a unit test (not part of this tut) to check your calculation.

Back to the page. Extend your source as in the following listing.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head >
        <title>Tiny calculator</title>
    </h:head>
    <h:body>
        <h1>Tiny calculator</h1>
        <h:form id="calculator">
          <h:outputLabel for="param1" value="Param 1:"/>
          <h:inputText id="param1" value="#{calculatorBean.param1}"/>
          <br/>
          <h:outputLabel for="param2" value="Param 2:"/>
          <h:inputText id="param2" value="#{calculatorBean.param2}"/>
          <br/>
          <h:commandButton action="#{calculatorBean.add}" value="add"/>
          <h:commandButton action="#{calculatorBean.substract}" value="substract"/>
          <h:commandButton action="#{calculatorBean.multiply}" value="multiply"/>
          <h:commandButton action="#{calculatorBean.divide}" value="divide"/>
          <br/>
          <h:outputLabel for="result" value="Result:"/>
          <h:outputText id="result" value="#{calculatorBean.result}"/>
        </h:form>
    </h:body>
</html>

On the one hand, form and texts got an id and the labels were bound to it. These ids   replace the automated generated and are much more readable.

On the other hand, the texts are bound to getter/setter. Because a single binding is valid for input and output, you have to ommit the “get” and “set”. Just use the rest of the methodname, with lower case first char. Internally this will be completed (precise: reflection will be used). Maybe you know properties from C#? Without these get/set it looks very similar to properties. Cool, isn’t it? And if you take a precise look to Microsoft’s CLR, you’ll recognize C# properties internally implemented be getter and setter. Oh wonderfull world of programming languages…

The calculation methods will be bound to the buttons. They simply trigger the method call. The result is bound as value (getter) to the outputText. For binding, expressions like “#{…}” are used. This is part of the unified expression language. More explanation to this topic later on. And now watch the result of the work done so far (start the app by pressing F6).

It looks like before. But now, when you enter two numbers and click a button, you’ll get a result.

And as by magic, invalid inputs will be commented and rejected.

I’ll talk about this later on…

 

To web development content.