Developing JSF applications

From IntelliJ-Wiki

Jump to: navigation, search

This tutorial shows how to develop and run JSF applications in IntelliJ IDEA. It offers a set of exercises that cover the overall application development cycle starting from project creation up to running and testing a completed JSF application in the context of a Web application server (Apache Tomcat):

Contents

Before you start

To be able to perform the tasks discussed in this tutorial, make sure that the following software is installed on your computer:

  • IntelliJ IDEA Ultimate Edition, version 12.
  • Java Development Kit (JDK), version 1.6 (also referred to as 6) or later. You can download the necessary version of Oracle JDK from the Java SE Downloads page.
  • Apache Tomcat, version 6 or later. You can download the necessary version of Tomcat from the Apache Tomcat page.
  • A Web browser.

Making sure that the necessary plugins are enabled

Plugins are extensions to IntelliJ IDEA core functionality. For the purposes of this tutorial, the following plugins have to be enabled in your copy of IntelliJ IDEA:

  • JSF Support
  • Tomcat and TomEE Integration

(The plugin names are self-explanatory, so their purposes seem to be obvious.)

To make sure that these plugins are enabled:

1. Start IntelliJ IDEA.

If you have just installed IntelliJ IDEA and are now running it for the first time, the Initial Configuration Wizard will come up at a certain stage of your interaction with the IDE. This wizard lets you disable the plugins that you are not going to use. (All the plugins bundled with the IDE are enabled by default.)

When you get to the page that shows Web and JavaEE plugins, make sure that the check box to the left of JSF is selected.

File:I12JSF01InitConfigWizardJSF.png

On the page that lists application server plugins, make sure that the check box next to Tomcat and TomEE is selected.

File:I12JSF02InitConfigWizardTomcatAndTomEE.png

Once you've done that, you can skip the rest of this section and proceed directly to registering Tomcat in IntelliJ IDEA.

If it's not the first time you are starting IntelliJ IDEA and you don't remember whether you have the JSF Support and the Tomcat and TomEE Integration plugins enabled, do the following:

2. Open the Settings dialog (e.g. by pressing CTRL+ALT+S).

3. In the left-hand part of the dialog under IDE Settings, click Plugins.

File:I12GF02SettingsPlugins.png‎

4. In the right-hand part of the dialog, on the Plugins page, type js in the search box. As a result, only the plugins whose names and descriptions contain js are shown in the list of plugins.

If the check box to the left of JSF Support is not selected, select it.

File:I12JSF03SettingsPluginsJSF.png

5. Find the Tomcat and TomEE Integration plugin and make sure that this plugin is enabled.

File:I12JSF04SettingsPluginsTomcatAndTomEE.png

6. Click OK in the Settings dialog.

7. If the plugins were not initially enabled, and you have selected to enable them, IntelliJ IDEA needs to restart for the changes to take effect. In this case the following dialog is displayed.

File:I12GF04RestartIDEA.png‎

Confirm that you’d like to restart IntelliJ IDEA by clicking Restart.

Now that you’ve made sure that the necessary plugins are enabled, you should register Tomcat in the IDE.

(For more information on working with plugins, see Managing Plugins in IntelliJ IDEA Help.)

Registering Tomcat in IntelliJ IDEA

To register Tomcat in IntelliJ IDEA:

1. Open the Settings dialog (e.g. CTRL+ALT+S).

2. In the left-hand part of the dialog under IDE Settings, click Application Servers.

File:I12GF05SettingsAppServers.png‎

3. In the right-hand part of the dialog, on the Application Servers page, click File:I12IconAdd.png (1), and then click Tomcat Server (2).

File:I12JSF05SettingsAppServersPlusTomcat.png

4. In the Tomcat Server dialog, click File:00_icon_ellipsis.png to the right of the Tomcat Home field.

File:I12JSF06TomcatServerDialogInitial.png

5. In the Tomcat Home Directory dialog, select the directory where you have Tomcat installed (1), and click OK (2).

File:I12JSF07TomcatHomeDirectoryDialog.png

6. Click OK in the Tomcat Server dialog.

File:I12JSF08TomcatServerDialogFinal.png

IntelliJ IDEA registers the .jar files necessary for working with Tomcat. You can see their list under Libraries. (An application server library that contains the corresponding files is created.)

File:I12JSF09SettingsAppServersFinal.png

7. Click OK in the Settings dialog.

IntelliJ IDEA is ready for working with Tomcat now.

Creating a new project

Any new development in IntelliJ IDEA starts with creating a project. (To find out why a project is needed, see Project in IntelliJ IDEA Help.)

So now we are going to create a project with a Java module, and support for Web application development and integration with Tomcat.

To create such a project:

1. If no project is currently open in IntelliJ IDEA, click Create New Project on the Welcome screen. Otherwise, select New Project from the File menu.

As a result, the New Project wizard opens.

2. In the left-hand pane, select Java Module (1).

3. In the right-hand part of the page, in the Project name field, type the name of your project (e.g. JSFDemo) (2).

File:I12JSF10NewProjectName.png

4. If the JDK that you are going to use is already defined in IntelliJ IDEA, select this JDK from the Project SDK list, click Next and proceed to the next step.

Otherwise, define the necessary JDK in the IDE and associate it with the project that you are creating. To do that:

Click New to the right of the Project SDK field (1) and select JDK (2).

File:I12SetUpProjectSDKWithSteps.png

In the Select Home Directory for JDK dialog that opens, select the directory in which you have the desired JDK installed (1), and click OK (2).

File:I12GF12JDKHome.png

The JDK you have just specified is shown in the Project SDK field.

File:I12JSF11NewProjectJDKSet.png

Click Next.

5. On the next page of the wizard, select the technologies to be supported in the project.

Because our application is going to be a Web application, select the Web Application check box.

Once you’ve done that, you can select the version of the Servlet specification to be supported.

File:I12JSF11NewProjectTechnologiesWebApp.png

The default version 2.5 will do for our exercises.

To add support for JSF, select the JSF check box. Make sure that the JSF version 2.0 and the Download option are selected. (When creating the project, IntelliJ IDEA will download a JSF 2.0 implementation library and associate it with your module.)

File:I12JSF12NewProjectTechnologiesJSF.png

We will also need integration with Tomcat in our project. To add support for this integration, select the Application Server check box. Make sure that the version of Tomcat you registered in IntelliJ IDEA earlier is selected in the Application Server list.

File:I12JSF13NewProjectTechnologiesAppServer.png

Click Finish to complete the wizard.

Wait while IntelliJ IDEA is creating the necessary project structures. When this process is complete, you can see the structure of your new project in the Project tool window.

Exploring the project structure

Let’s have a look at the project structure created by IntelliJ IDEA.

File:I12JSF14ProjectToolWindowInitialState.png

There are two top-level nodes in this structure:

  • JSFDemo. This node represents your module. Within this node:
    • The .idea folder and the file JSFDemo.iml are used to store configuration data for your project and module respectively.
    • The lib folder contains the .jar files pertaining to the JSF 2.0 implementation library.
    • The src folder is intended for Java source files.
    • The web folder is for your Web application assets such as Web pages, images, style sheets, configuration files, etc. This folder already contains the subdirectory WEB-INF with the JSF configuration file faces-config.xml and Web application deployment descriptor web.xml. Also in the web folder is the file index.jsp. This is a one-page Hello, World JSF application provided for demo purposes.
  • External Libraries. This is a category that represents all the "external" resources necessary for your development work. Currently in this category are the .jar files that make up your JDK and the Tomcat .jar library files.

(For more information on tool windows in general and the Project tool window in particular, see IntelliJ IDEA Tool Windows and Project Tool Window in IntelliJ IDEA Help.)

The Hello, World JSF application

The Hello, World JSF application is implemented by index.jsp located in the web directory. This file has been created by IntelliJ IDEA automatically to illustrate the basics of JSF. In a moment, we'll run this application to make sure that everything is fine with the project configuration and infrastructure. Before doing that, however, let's have a quick look at the source code to see what to expect.

Opening the source file in the editor

To see the source code of index.jsp, open the file in the editor. In the Project tool window, do one of the following:

  • Double-click the file.
  • Select the file and press F4.
  • Right-click the file and select Jump to Source from the context menu.

As a result, the file opens. The source code looks similar to this:

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head><title>Simple jsp page</title></head>
  <body>

  <f:view>
      <h:outputLabel value="Hello, world"/>
  </f:view>

  </body>
</html>

As you can see, the only purpose of this page is to output the text Hello, world.

Running the application

To run the application, do one of the following:

  • Click File:I12RunIcon.png‎ on the toolbar.

File:I12JSF15Run.png

  • Select Run from the Run menu.
  • Press SHIFT+F10.

As a result, IntelliJ IDEA builds the application, starts Tomcat and deploys the application to the server. You can monitor the process in the Run tool window that opens at the bottom of the screen. (This tool window is responsible for displaying all the output from executed run configurations. For more information, see Run Tool Window in IntelliJ IDEA Help.)

File:I12JSF16RunToolWindow.png

After a while, your default Web browser starts and the following page is shown.

File:00101_hello_world_in_browser.png

If this is so, then everything's working fine. Let's now close the browser, stop the server (File:I12StopIcon.png in the Run tool window (1) or CTRL+F2) and close the Run tool window (File:I12CloseIcon.png (2) or CTRL+F4).

File:I12JSF17RunToolWindowStopAndClose.png

What made it possible to run the application?

To make running and testing our JSF application easier, IntelliJ IDEA, as part of the project infrastructure, has automatically created the following:

  • A properly configured application artifact, i.e. the specification of an application to be produced.
  • A run configuration for building, deploying and running the application artifact in the context of Tomcat.

Now we are going to take a quick look at these configurations.

Exploring an application artifact

Artifacts in IntelliJ IDEA may mean two different but related things. First of all, the artifacts (or, to be more precise, artifact configurations) are the blueprints (or specifications) of the outputs that we want to be generated for our project. These are shown, created and edited in the Artifacts section of the Project Structure dialog.

In the second sense, the artifacts are the actual outputs generated according to the corresponding blueprints (or the artifact configurations).

At the moment, one artifact configuration already exists. Let's now study this configuration:

1. Open the Project Structure dialog (File | Project Structure, File:I12ProjectStructureIcon.png on the toolbar, or CTRL+ALT+SHIFT+S).

2. Under Project Settings, select Artifacts.

File:I12GF19ProjectStructureArtifacts.png‎

As you can see, there is already one artifact configuration there (JSFDemo:war exploded). The settings for this artifact are shown in the right-hand part of the dialog under Artifact 'JSFDemo:war exploded'.

File:I12JSF18ArtifactSettings.png

The artifact type is Web Application: Exploded. This type corresponds to a decompressed Web application archive (WAR), a directory structure that is ready for deployment on a Web server.

For the purposes of testing our sample application, this output format seems to be the best.

The artifact, when built, is placed into <project_folder>\out\artifacts\JSFDemo_war_exploded. This is specified in the Output directory field.

The artifact layout is shown in the left-hand pane of the Output Layout tab.

The <output root> at the top represents the output directory (<project_folder>\out\artifacts\JSFDemo_war_exploded). The rest of the elements shown have the following meanings (and are directly related to corresponding source directories and resources that we have already seen in the Project tool window when exploring the project structure):

  • The WEB-INF directory corresponds to the project directory WEB-INF with all its contents. (When the artifact is built, the project directory WEB-INF with all its contents is copied into the output directory.)
  • 'JSFDemo' compile output represents compiled Java classes whose sources are located in the src project directory. As you can see, these are placed into WEB-INF\classes in the output directory.
  • lib corresponds to the lib project directory with the .jar files pertaining to the JSF 2.0 library. When building the artifact, these .jar files are copied into WEB-INF\lib.
  • 'Web' facet resources represent your Web pages, images, style sheets, configuration files, etc. contained in the project folder web.

To see a more detailed picture of the artifact configuration, select the Show content of elements check box.

File:I12JSF19ArtifactSettingsDetailed.png

To see that the configuration shown corresponds to the actual structure and contents of the artifact, you can go to the directory <project_folder>\out\artifacts\JSFDemo_war_exploded and explore its contents. (The artifact contained there was built when we ran the Hello, World application.)

So, the artifact specification looks fine.

3. Click OK in the Project Structure dialog.

Now let's look at the run configuration (that we already used to run Hello, World and will also use to run our sample application) and adjust it to our needs.

(For more information on working with artifacts, see Configuring Artifacts and Artifacts in IntelliJ IDEA Help.)

Exploring a run configuration and adjusting its settings

Applications in IntelliJ IDEA are run according to what is called run/debug configurations. Such configurations, generally, should be created prior to running an application. (For more information, see Running, Debugging and Testing in IntelliJ IDEA Help.)

In our case, we don't need to create a run configuration. IntelliJ IDEA has already created one for us for running the application artifact in the context of Tomcat. Let's now have a look at its settings and perform minor adjustments.

1. Open the Run/Debug Configurations dialog. To do that, select Edit Configurations (2) from the Run menu (1):

File:I12JSF20RunEditConfigurations.png

or Edit Configurations from the run configuration selector on the toolbar:

File:I12JSF21EditConfigurationsInSelector.png

The only existing run configuration (which has the name of the Tomcat version that you are using) is selected and its settings are shown in the right-hand part of the dialog.

File:I12JSF22RunConfig.png

Note that the Start browser check box is selected under Open browser. This means that the default Web browser on your computer should be started.

The Startup page field specifies the URL the Web browser should go to when started. The current setting http://localhost:8080/index.faces corresponds to the page index.jsp that we saw in the browser when we ran the Hello, World application using this configuration.

File:I12JSF23RunConfigBrowserSettings.png

2. Let's change the URL to http://localhost:8080/. This is the URL that will be associated with the starting page of the application that we are going to develop.

File:I12JSF24RunConfigStartupPageChanged.png

The On 'Update' action and On frame deactivation options define how and when your application is updated on the server. (Frame deactivation means switching from IntelliJ IDEA to a different application, for example, a Web browser.)

3. We are going to update our application by means of the Update action. Each time when doing so, we will redeploy the application. So, select Redeploy from the On 'Update' action list.

Leave the Show dialog check box selected. This will give you an additional option of selecting the necessary Update action prior to actually performing the update.

File:I12JSF25RunConfigUpdateActionChanged.png

The Before launch options define the actions to be performed when the Run configuration is activated (i.e. run or rerun). As you can see, IntelliJ IDEA will build your application artifact (JSFDemo:war exploded) each time before running it. (For example, if you make changes to your source code, IntelliJ IDEA will build all the files affected by these changes before running the application.)

File:I12JSF26RunConfigBeforeLaunch.png

If you switch to the Deployment tab, you'll see that the IDE will deploy (or redeploy) the application artifact each time the server is started or restarted.

Click the artifact. The Application context field is displayed which is used for assigning a context root to the artifact. The default setting / (which we'll leave unchanged) associates our application with the root context. Note that this setting is in accord with the URL the Web browser is directed to at its start (http://localhost:8080/).

File:I12JSF27RunConfigDeployment.png

You can browse the remaining tabs for more settings. Their discussion, however, is beyond the scope of this tutorial.

4. Click OK in the Run/Debug Configurations dialog.

A sample JSF application

To demonstrate how IntelliJ IDEA supports JSF, we will develop a sample JSF application.

The logic of the sample application

Our sample application is going to be a very basic one. It will convert meters into inches.

File:00501_pages.png

A user is asked to input the number of meters for conversion into inches (screen 1). If a valid number is entered, the application performs the conversion and shows the result (screen 2a). If the user specifies anything other than a number or provides no input, he or she gets an error screen (screens 2b and 2c).

The structure of the sample application

The sample application will contain two JSF pages, namely:

  • input_number.xhtml implementing screen 1. This page will accept the user's input and submit it to the server.
  • result.xhtml implementing screens 2a, 2b and 2c. This page will show the result or inform the user about an error.

The backing bean converterBean will be used to convert the input number of meters into inches. It will also provide the heading text (CONVERSION RESULT or CONVERSION FAILED) and the text for the button label (Convert another number or Try once more) for the result page. The bean will be implemented by the ConverterBean class.

The configuration file faces-config.xml will contain the converterBean definition and also the navigation rules for switching between the pages.

The deployment descriptor web.xml, among other things, will associate the Faces Servlet with our Facelets (the xhtml pages). It will also define the page input_number.xhtml as the starting page of the application.

The source code

This section shows the contents of all the source files used in the sample application in their final form. Note that certain fragments in these files are on yellow background and the font colors are about the same as in the editor:

When creating a file, IntelliJ IDEA, as a rule, provides some initial content appropriate for the file type. The grey background is used to show the fragments provided by the IDE that will be left unchanged. Changed or added fragments have yellow background.

input_number.xhtml

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="METERS TO INCHES CONVERSION"/><br/><br/>
    <h:form>
        <h:outputText value="Enter amount in meters (m):"/>&nbsp;
        <h:inputText value="#{converterBean.result}" size="16"/><br/><br/>
        <h:commandButton action="result" value="Convert into inches"/>
    </h:form>
</h:body>

</html>

result.xhtml

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="#{converterBean.conversionSummary}"/><br/><br/>
    <h:outputText value="#{converterBean.result}"/><br/><br/>
    <h:form>
        <h:commandButton action="back" value="#{converterBean.buttonLabel}"/>
    </h:form>
</h:body>

</html>

converterBean (ConverterBean.java)

public class ConverterBean {
    private String result;
    private String conversionSummary;
    private String buttonLabel;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        double conversionFactor = 39.37;
        try {
            double metersToConvert = Double.parseDouble(result);
            double inches = conversionFactor*metersToConvert;
            String inchesString = Double.toString(inches);
            this.result = result + " m = " + inchesString + " inches";
            setConversionSummary("CONVERSION RESULT");
            setButtonLabel("Convert another number");
        } catch (NumberFormatException e) {
            this.result = "\"" + result + "\" is not a number.";
            if (result.isEmpty()) this.result = "You forgot to specify the number of meters.";
            setConversionSummary("CONVERSION FAILED");
            setButtonLabel("Try once more");
        }
    }

    public String getConversionSummary() {
        return conversionSummary;
    }

    public void setConversionSummary(String conversionSummary) {
        this.conversionSummary = conversionSummary;
    }

    public String getButtonLabel() {
        return buttonLabel;
    }

    public void setButtonLabel(String buttonLabel) {
        this.buttonLabel = buttonLabel;
    }
}

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
              version="2.0">
    <managed-bean>
        <managed-bean-name>converterBean</managed-bean-name>
        <managed-bean-class>ConverterBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/input_number.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>result</from-outcome>
            <to-view-id>/result.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/result.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>back</from-outcome>
            <to-view-id>/input_number.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>input_number.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Creating an initial version of the application

Let's start by creating an application containing only one starting page (input_number.xhtml).

Creating input_number.xhtml

To create the starting page of our sample application:

1. In the Project tool window, select the web directory and press ALT+INSERT to open the New menu. Then select JavaEE Web Page from this menu.

File:I12JSF28CreateJavaEEWebPage.png

(There are also alternative ways of creating new files in IntelliJ IDEA. You can use the File menu (File | New) or the context menu for a directory or package in the Project tool window.)

2. In the Create JavaEE Web Page dialog, type the name of the page (input_number) in the Name field. Select Facelets page from the Kind list and click OK. (When the cursor is in the Name field, you can use the UP and DOWN arrow keys to move between the options of the Kind list. Besides, you can press ENTER instead of clicking OK.)

File:I12JSF29CreateInputNumberFaceletsPage.png

As a result, the file input_number.xhtml is created and opened in the editor.

File:I12JSF30InputNumberInitial.png

Editing input_number.xhtml

Let's now develop the initial version of this page that we could test. The initial version of the page will be "static" and its source will look as follows (the changed and new fragments are on yellow background):

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="METERS TO INCHES CONVERSION"/><br/><br/>
    <h:outputText value="Enter amount in meters (m):"/>&nbsp;
    <h:inputText size="16"/><br/><br/>
    <h:commandButton value="Convert into inches"/>
</h:body>

</html>

1. Change the content of the <title> element to JSF Demo.

File:I12JSF31InputNumberChangeTitle.png

2. In the <h:body> element, delete the text Place your content here.

Now we are going to add the line

<h:outputText value="METERS TO INCHES CONVERSION"/><br/><br/>

To do that:

3. Type <h:o and select h:outputText from the code completion suggestion list. (Use the UP and DOWN arrow keys to move within the list and ENTER for selecting highlighted list item.)

File:I12JSF32InputNumberAddOutputText.png

4. Type space, type v and select value. (You can use the TAB key to select the first item in the suggestion list.)

File:I12JSF33InputNumberAddValue.png

5. Type METERS TO INCHES CONVERSION inside the quotation marks. Go to the end of the line (press END) and type / to close the tag. Then type <br/><br/> and press ENTER to start a new line.

6. Using the code completion techniques demonstrated above, add the remaining lines:

<h:outputText value="Enter amount in meters (m):"/>&nbsp;
<h:inputText size="16"/><br/><br/>
<h:commandButton value="Convert into inches"/>

Finally, the markup in the editor should look similar to this (only the <h:body> element is shown):

File:I12JSF34InputNumberIter1Result.png

Modifying web.xml

To associate the Faces Servlet with the URL pattern *.xhtml and also make input_number.xhtml the starting page of the application, we are going to add the following into web.xml:

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>input_number.xhtml</welcome-file>
</welcome-file-list>

As a result, web.xml will contain:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>input_number.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

1. Open web.xml in the editor.

If you want to do that using only the keyboard, you can use 1) ALT+1 to switch to the Project tool window, 2) the UP or DOWN arrow key to move to web.xml, 3) F4 to open the file.

Another alternative is to press CTRL+SHIFT+N and start typing the file name. When the file of interest shows up in the list, use the UP and DOWN arrow keys to move to the file and ENTER to open it.

2. Place the cursor at the end of the last closing </servlet-mapping> tag and press ENTER to start a new line. (Alternatively, you can place the cursor anywhere within the corresponding line and press SHIFT+ENTER.)

3. Now we are going to use the code generation feature which you can access in one of the following ways:

  • Select Code | Generate.
  • Use a right click to open the context menu and select Generate.
  • Press ALT+INSERT.

4. Select XML Tag from the Generate menu.

File:I12JSF35WebXmlGenerateXmlTag.png

5. When the Choose Tag Name menu is shown, type se to see the tags whose names contain se. Then select servlet-mapping.

File:I12JSF36WebXmlAddServletMapping.png

The <servlet-mapping> element is generated and the cursor is placed between the opening and closing <servlet-name> tags. At the same time, the suggestion list appropriate for the current cursor position is shown.

6. Select Faces Servlet from this list.

The selected content of the <servlet-name> element is generated and the cursor is placed between the opening and closing <url-pattern> tags.

7. Type *.xhtml

File:I12JSF37WebXmlUrlPattern.png

and press ESCAPE. Then press ENTER to start a new line.

8. In a similar way, add:

<welcome-file-list>
    <welcome-file>input_number.xhtml</welcome-file>
</welcome-file-list>

Once you've done that, all the necessary mappings are there.

File:I12JSF38WebXmlMappingsAdded.png

Running the application

1. Run the application (SHIFT+F10 or File:I12RunIcon.png on the toolbar).

IntelliJ IDEA builds the application, starts Tomcat and deploys the application to the server. Then your Web browser starts and the following page is shown:

File:00201_input_number_in_browser.png

So, we've got the expected page and it looks properly. There's nothing else to check at the moment.

2. Leave the page and the browser open, and switch to IntelliJ IDEA.

Adding navigation

Now, we are going to turn our application into a two-page application and add the ability to switch between the pages. To achieve this, we'll make the corresponding changes to input_number.xml, create another page (result.xhtml) and develop an initial layout for it, and specify the necessary navigation rules in faces-config.xml.

Modifying input_number.xhtml

The markup after the changes that we are going to make will look this way:

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="METERS TO INCHES CONVERSION"/><br/><br/>
    <h:form>
        <h:outputText value="Enter amount in meters (m):"/>&nbsp;
        <h:inputText size="16"/><br/><br/>
        <h:commandButton action="result" value="Convert into inches"/>
    </h:form>
</h:body>

</html>

As you can see, we will add the <h:form> element and the action attribute (action="result") to be able to link the page to the navigation rule that we are going to develop a bit later.

This is how you make the corresponding edits in IntelliJ IDEA.

First, we will use the Surround With function to wrap the corresponding elements in <h:form>...</h:form>.

1. Select the fragment you are going to surround with <h:form>...</h:form>.

File:I12JSF39InputNumberSelectFragmentToSurround.png

2. To access the Surround With function, do one of the following:

  • Press CTRL+ALT+T.
  • Select Code | Surround With (1, 2).

File:I12JSF40CodeSurroundWith.png

3. Select T2. Surround with <tag></tag> in HTML/JSP from the Surround With menu.

File:I12JSF41SurroundWithMenu.png

4. Type h, select h:form and press ESCAPE.

File:I12JSF42InputNumberAddForm.png

5. Add action="result" to the <h:commandButton> element.

The page is now ready for linking to a navigation rule.

File:I12JSF43InputNumberActionAdded.png

Creating result.xhtml

Now we are going to create the JSF page result.xhtml.

1. In the Project tool window, select the folder web and press ALT+INSERT.

2. In the New menu, select JavaEE Web Page.

File:I12JSF44AddJavaEEWebPage2.png

3. In the Create JavaEE Web Page dialog, type result in the Name field, select Facelets page from the Kind list and click OK.

File:I12JSF45CreateFaceletsPageResult.png

As a result, the page result.xhtml is created and opened in the editor.

Editing result.xhtml

Now we are going to develop the initial page layout and prepare the page for linking to a navigation rule. The resulting markup will look this way:

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="CONVERSION RESULT"/><br/><br/>
    <h:outputText value="1 m = 39.37 inches"/><br/><br/>
    <h:form>
        <h:commandButton action="back" value="Convert another number"/>
    </h:form>
</h:body>

</html>

1. Change the content of the <title> element to JSF Demo.

2. Within the <h:body> element, replace the text Place your content here with the following:

<h:outputText value="CONVERSION RESULT"/><br/><br/>
<h:outputText value="1 m = 39.37 inches"/><br/><br/>
<h:form>
    <h:commandButton action="back" value="Convert another number"/>
</h:form>

The corresponding elements in result.xhtml will now look similar to this:

File:I12JSF46ResultIter1.png

Specifying the navigation rules

To specify navigation rules, we'll add the corresponding elements into the JSF configuration file faces-config.xml. As a result, the markup in faces-config.xml will look similar to this:

<?xml version='1.0' encoding='UTF-8'?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
              version="2.0">
    <navigation-rule>
        <from-view-id>/input_number.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>result</from-outcome>
            <to-view-id>/result.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/result.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>back</from-outcome>
            <to-view-id>/input_number.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

The task can be performed by editing the code and using tag generation in combination with code completion as was shown for input_number.xhtml and web.xml. The other alternative (that we are about to demonstrate) is to use the GUI features provided by IntelliJ IDEA for editing JSF configuration files.

1. Open faces-config.xml for editing.

Now we a going to create the navigation rule for switching from input_number.xhtml to result.xhtml.

2. Select the Navigation tab in the lower-left part of the editor area.

File:I12JSF47FacesConfigTabsText.png

3. Drag the file input_number.xhtml from the Project tool window into the editor. Do the same with the file result.xhtml. Draw a line from /input_number.xhtml to /result.xhtml.

File:I12JSF48FacesConfigNavigation1.png

4. Switch onto the Structure tab.

File:I12JSF49FacesConfigTabsNavigation.png

5. In the left-hand pane, expand the Navigation Rules node (1) and select /input_number.xhtml (2).

6. In the From Outcome field, type result (3).

File:I12JSF50FacesConfigStructure.png

7. Switch onto the Text tab to see the navigation rule that has been generated (<navigation-rule>...</navigation-rule>).

File:I12JSF51FacesConfigNavRuleAdded.png

In a similar way, create the navigation rule for switching from result.xhtml to input_number.xhtml:

8. Switch onto the Navigation tab and draw a line from /result.xhtml to /input_number.xhtml. As a result, the diagram will look similar to this:

File:I12JSF52FacesConfigAnotherLineDrawn.png

9. Switch onto the Structure tab and, under Navigation Rules, select /result.xhtml. In the From Outcome field, type back.

10. Switch onto the Text tab to see the result.

File:I12JSF53FacesConfigNavRulesAdded.png

Updating and running the application

Now we are going to check the navigation.

1. Update the application:

Click File:00_icon_update.png in the Run tool window or press CTRL+F10.

File:I12JSF54RunToolWindowUpdate.png

In the Update dialog, make sure that Redeploy is selected and click OK. (Select Don't ask again if you don't want to see this dialog each time when updating the application.)

File:I12JSF55UpdateDialog.png

Wait while the application is being redeployed (monitor the output in the Run tool window).

At this step, IntelliJ IDEA may fail to redeploy the application and you won't see any output in the Output pane of the Run tool window. If this happens: 1) Restart IntelliJ IDEA. 2) Execute the run configuration (File:I12RunIcon.png). 3) When the starting page of the application shows up in the browser, continue from step 3 below.

2. Switch to the Web browser. Make sure that the URL in the address field is http://localhost:8080. You may also need to refresh (or reload) the page.

3. On the starting page of the application, click Convert into inches.

File:00301_input_number_in_browser.png

The result page is displayed.

4. Click Convert another number on this page.

File:00302_result_in_browser.png

You are back to the starting page. So the navigation works fine.

5. Leave the browser open and switch to IntelliJ IDEA.

Creating a backing bean and wiring it up to the application

Now we are going to create an initial, very simple version of a backing bean for our JSF application and connect it to our application (that is, define the bean in faces-config.xml and add references to its only field to the JSF pages.)

We could create the bean class and then define it in faces-config.xml. We will, however, follow a different scenario. We will start with the bean definition in faces-config.xml and then use a quick fix provided by IntelliJ IDEA to create the bean class.

Adding bean definition to faces-config.xml

In this exercise we will add the bean definition by editing the markup in faces-config.xml (on the Text tab). There is also another alternative for performing this task, by using the GUI provided on the Structure tab. The procedure, in a way, is similar to that used for specifying the navigation rule.

By the end of the exercise, faces-config.xml will contain the following:

<?xml version='1.0' encoding='UTF-8'?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
              version="2.0">
    <managed-bean>
        <managed-bean-name>converterBean</managed-bean-name>
        <managed-bean-class>ConverterBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/input_number.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>result</from-outcome>
            <to-view-id>/result.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/result.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>back</from-outcome>
            <to-view-id>/input_number.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

1. In faces-config.xml (on the Text tab), place the cursor at the end of the opening <faces-config> tag. Press ENTER to start a new line.

2. Press ALT+INSERT to open the Generate menu. Select Managed Bean (1) and then select Property Bean (2).

File:I12JSF56FacesConfigAddManagedBean.png

When the <managed-bean/> tag is generated, note that this tag is underlined in red. This indicates that there is a problem with this tag. Also note the light bulb File:I12ErrorIcon.png showing that a quick fix is available.

File:I12JSF57FacesConfigManagedBeanProblem.png

3. Click the light bulb or press ALT+ENTER to see the list of suggested quick fixes. Select Insert Required Child Tag managed-bean-name.

File:I12JSF58FacesConfigAddManagedBeanName.png

4. In a similar way, insert the tags <managed-bean-class/> and <managed-bean-scope/>.

5. Place the cursor within <managed-bean-name/>, press ALT+ENTER and select Expand Empty Tag.

File:I12JSF59FacesConfigManagedBeanExpandTag.png

6. Between <managed-bean-name> and </managed-bean-name>, type converterBean.

File:I12JSF60FacesConfigBeanNameSpecified.png

7. Expand the tags <managed-bean-class/> and <managed-bean-scope/>. Between <managed-bean-class> and </managed-bean-class>, type ConverterBean. Between <managed-bean-scope> and </managed-bean-scope>, type request.

File:I12JSF61FacesConfigBeanElementsDefined.png

8. Place the cursor within ConverterBean, press ALT+ENTER and select Create Class ConverterBean.

File:I12JSF62FacesConfigCreateBeanClass.png

As a result, the file ConverterBean.java is created (in the src directory) and opened in the editor.

File:I12JSF63BeanClassCreated.png

Editing the ConverterBean class

Now we are going to add one field (result) and generate the getter and setter methods for it. The source code at the end of this exercise will look similar to this:

public class ConverterBean {
    private String result;

    public String getResult() {
        return result;
    }
 
    public void setResult(String result) {
        this.result = result;
    }
}

1. Press SHIFT+ENTER to start a new line after public class ConverterBean {.

2. Add the following field declaration:

private String result;

Note that the field name result is shown in gray. If you point to result, you'll see the text reading Private field 'result' is never used. (The gray color in the editor is used to indicate unused entities.)

3. Place the cursor within result, press ALT+ENTER and select Create getter and setter for 'result'.

File:I12JSF64CreateGetterAndSetterForResult.png

As a result, the methods getResult() and setResult() are generated. Note that at the moment both these method are shown as unused (gray).

File:I12JSF65GetterAndSetterCreated.png

Now we are going to resolve this issue by adding references to the field result on the pages input_number and result.

Adding a reference to the bean field result in input_number.xhtml

By the end of this editing session, the markup in input_number.xhtml will look as follows:

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="METERS TO INCHES CONVERSION"/><br/><br/>
    <h:form>
        <h:outputText value="Enter amount in meters (m):"/>&nbsp;
        <h:inputText value="#{converterBean.result}" size="16"/><br/><br/>
        <h:commandButton action="result" value="Convert into inches"/>
    </h:form>
</h:body>

</html>

1. In the editor, switch onto the input_number.xhtml tab. (You can use CTRL+ALT+LEFT/RIGHT which work similarly to Back/Forward in a Web browser, or the IntelliJ IDEA Switcher accessed by means of CTRL+TAB.)

2. Add value="#{converterBean.result}" within the <h:inputText> tag.

File:I12JSF66InputNumberReferenceToBeanAdded.png

3. Now we are going to add the same reference on the page result. The quickest way to do that is by means of copying and pasting. So, copy the fragment value="#{converterBean.result}" to the clipboard (CTRL+C).

Adding a reference to the bean field result in result.xhtml

By the end of this editing session the markup in result.xhtml will be as follows:

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="CONVERSION RESULT"/><br/><br/>
    <h:outputText value="#{converterBean.result}"/><br/><br/>
    <h:form>
        <h:commandButton action="back" value="Convert another number"/>
    </h:form>
</h:body>

</html>

1. In the editor, switch onto the result.xhtml tab.

2. Replace the fragment value="1 m = 39.37 inches" with the contents of the clipboard (value="#{converterBean.result}", CTRL+V).

File:I12JSF67ResultReferenceToBeanAdded.png

Updating and running the application

Now we are going to make sure that the bean functions properly.

1. Update the application: CTRL+F10 or File:00_icon_update.png in the Run tool window.

2. Switch to the Web browser. Make sure that the URL in the address field is http://localhost:8080. You may also need to refresh (or reload) the page.

3. On the starting page, type something (for example, TEN) in the Enter amount in meters (m) field (1) and click Convert into inches (2).

File:00401_input_number_in_browser.png

The result page is shown looking something like this:

File:00402_result_in_browser.png

4. Click Convert another number to come back onto the starting page.

So, it looks like everything's fine with the bean.

5. Switch to IntelliJ IDEA.

Adding the conversion code to the ConverterBean class

Now we are going to modify the application so that the number of meters input by a user is converted into inches. This will be done by adding the conversion code to the setResult() method of the ConverterBean class.

Modifying the ConverterBean class

By the end of this editing session the code of the ConverterBean class will be as follows:

public class ConverterBean {
    private String result;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        double conversionFactor = 39.37;
        double metersToConvert = Double.parseDouble(result);
        double inches = conversionFactor*metersToConvert;
        String inchesString = Double.toString(inches);
        this.result = result + " m = " + inchesString + " inches";
    }
}

1. In the editor, switch onto the ConverterBean.java tab.

2. After

public void setResult(String result) { 

start a new line and add

double conversionFactor = 39.37;
double metersToConvert = Double.parseDouble(result);
double inches = conversionFactor*metersToConvert;
String inchesString = Double.toString(inches);

3. Change

this.result = result; 

to

this.result = result + " m = " + inchesString + " inches";

File:I12JSF68BeanCoversionCodeAdded.png

The conversion code at this step is ready. Let's see how it works.

Updating and running the application

1. Update the application (CTRL+F10 or File:00_icon_update.png in the Run tool window).

2. Switch to the Web browser. Make sure that the URL in the address field is http://localhost:8080. You may also need to refresh (or reload) the page.

3. On the starting page, type 1 in the Enter amount in meters (m) field (1) and click Convert into inches (2).

File:00501_input_number_in_browser.png

The result page is displayed showing the conversion result.

File:00502_result_in_browser.png

4. Try to convert other numbers to make sure that the conversion works fine.

Now try the conversion for the cases when no input is provided and when anything other than a number is input. In both cases an error page is returned containing an exception report. Let's handle the exceptional cases in the code of the ConverterBean class.

5. Switch to IntelliJ IDEA.

Finalizing the application

In the ConverterBean class, we will add the code for handling the corresponding exceptions. We will also add two new fields, generate getter and setter methods for them, and add references to these new fields on the result page.

Surrounding the conversion code with the try/catch block

The ConverterBean class is going to be changed like this:

public class ConverterBean {
    private String result;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        double conversionFactor = 39.37;
        try {
            double metersToConvert = Double.parseDouble(result);
            double inches = conversionFactor*metersToConvert;
            String inchesString = Double.toString(inches);
            this.result = result + " m = " + inchesString + " inches";
        } catch (NumberFormatException e) {
            this.result = "\"" + result + "\" is not a number.";
            if (result.isEmpty()) this.result = "You forgot to specify the number of meters.";
        }
    } 
}

1. In the editor, switch onto the ConverterBean.java tab.

2. Within the setResult() method, select the conversion code block, press CTRL+ALT+T and select try / catch from the menu.

File:I12JSF69BeanSurroundWithTryCatch.png

3. Replace the line that contains e.printStackTrace(); with the following:

this.result = "\"" + result + "\" is not a number.";
if (result.isEmpty()) this.result = "You forgot to specify the number of meters.";

At this step the exceptional cases seem to be properly handled.

File:I12JSF70BeanTryCatchBlockCompleted.png

Finalizing the code for the ConverterBean class

Now we are going to add two more fields to the ConverterBean class. The first of the fields (conversionSummary) will be used for displaying the first line on the result page depending on whether the conversion succeeded or failed (CONVERSION RESULT or CONVERSION FAILED). The second of the fields (buttonLabel) will hold two different versions of the button label for the result page (Convert another number if the conversion is a success and Try once more if the conversion failed).

public class ConverterBean {
    private String result;
    private String conversionSummary;
    private String buttonLabel;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        double conversionFactor = 39.37;
        try {
            double metersToConvert = Double.parseDouble(result);
            double inches = conversionFactor*metersToConvert;
            String inchesString = Double.toString(inches);
            this.result = result + " m = " + inchesString + " inches";
            setConversionSummary("CONVERSION RESULT");
            setButtonLabel("Convert another number");
        } catch (NumberFormatException e) {
            this.result = "\"" + result + "\" is not a number.";
            if (result.isEmpty()) this.result = "You forgot to specify the number of meters.";
            setConversionSummary("CONVERSION FAILED");
            setButtonLabel("Try once more");
        }
    }

    public String getConversionSummary() {
        return conversionSummary;
    }

    public void setConversionSummary(String conversionSummary) {
        this.conversionSummary = conversionSummary;
    }

    public String getButtonLabel() {
        return buttonLabel;
    }

    public void setButtonLabel(String buttonLabel) {
        this.buttonLabel = buttonLabel;
    }
}

1. Place the cursor within the line

private String result;

and press SHIFT+ENTER to start a new line.

2. Add the line

private String conversionSummary;

3. Place the cursor within conversionSummary, press ALT+ENTER and select Create getter and setter for 'conversionSummary'.

File:00501_getter_and_setter.png

Within the setResult() method, add calls to setConversionSummary():

4. After the line

this.result = result + " m = " + inchesString + " inches";

add

setConversionSummary("CONVERSION RESULT");

5. After the line

if (result.isEmpty()) this.result = "You forgot to specify the number of meters.";

add

setConversionSummary("CONVERSION FAILED");

File:I12JSF71BeanSetConversionSummary.png

6. In a similar way, add the field buttonLabel and generate getter and setter methods for it.

Add calls to setButtonLabel() to setResult():

7. After the line

setConversionSummary("CONVERSION RESULT");

add

setButtonLabel("Convert another number");

8. After the line

setConversionSummary("CONVERSION FAILED");

add

setButtonLabel("Try once more");

At this step the code of ConverterBean is completed.

File:I12JSF72BeanButtonLabelSet.png

Adding references to the new fields on the result page

We are now going to bring the markup in result.xhtml to the following state:

<?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>JSF Demo</title>
</h:head>

<h:body>
    <h:outputText value="#{converterBean.conversionSummary}"/><br/><br/>
    <h:outputText value="#{converterBean.result}"/><br/><br/>
    <h:form>
        <h:commandButton action="back" value="#{converterBean.buttonLabel}"/>
    </h:form>
</h:body>

</html>

1. In the editor, switch onto the result.xhtml tab.

2. In the first of the <h:outputText> elements, replace

value="CONVERSION RESULT" 

with

value="#{converterBean.conversionSummary}"

3. In the <h:commandButton> tag, replace

value="Convert another number" 

with

value="#{converterBean.buttonLabel}"

File:I12JSF73ResultReferencesAdded.png

At this step, the code of the overall application is ready. All that's left is to make sure that this is the case.

Updating and running the application

Update and run the application as you did before. Make sure that the application now works fine.

1. For the case when no input is provided:

File:BrowserConvertNothing.png

you should now get the page looking like this:

File:ResultForConvertNothing.png

2. When trying to convert anything other than a number:

File:ConvertStringTen.png

you are now appropriately informed about that:

File:ResultForConvertStringTen.png

This is, basically, it: our application is working fine. At this step, our exercises are complete and, hopefully, you now have an impression of how to develop JSF applications in IntelliJ IDEA.

Personal tools