Home > Articles > Programming > Java

This chapter is from the book

6.3 A Web Module That Uses JavaServer Faces Technology: The hello1 Example

The hello1 application is a web module that uses JavaServer Faces technology to display a greeting and response. You can use a text editor to view the application files, or you can use NetBeans IDE.

The source code for this application is in the tut-install/examples/web/jsf/hello1/ directory.

6.3.1 To View the hello1 Web Module Using NetBeans IDE

  1. From the File menu, choose Open Project.
  2. In the Open Project dialog box, navigate to:

    tut-install/examples/web/jsf
  3. Select the hello1 folder and click Open Project.
  4. Expand the Web Pages node and double-click the index.xhtml file to view it in the editor.

    The index.xhtml file is the default landing page for a Facelets application. In a typical Facelets application, web pages are created in XHTML. For this application, the page uses simple tag markup to display a form with a graphic image, a header, a field, and two command buttons:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html lang="en"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://xmlns.jcp.org/jsf/html">
        <h:head>
            <title>Facelets Hello Greeting</title>
        </h:head>
        <h:body>
            <h:form>
                <h:graphicImage url="#{resource['images:duke.waving.gif']}"
                                alt="Duke waving his hand"/>
                <h2>Hello, my name is Duke. What's yours?</h2>
                <h:inputText id="username"
                             title="My name is: "
                             value="#{hello.name}"
                             required="true"
                             requiredMessage="Error: A name is required."
                             maxlength="25" />
                <p></p>
                <h:commandButton id="submit" value="Submit"
                                 action="response" />
                <h:commandButton id="reset" value="Reset" type="reset" />
            </h:form>
            ...
        </h:body>
    </html>

    The most complex element on the page is the inputText field. The maxlength attribute specifies the maximum length of the field. The required attribute specifies that the field must be filled out; the requiredMessage attribute provides the error message to be displayed if the field is left empty. The title attribute provides the text to be used by screen readers for the visually disabled. Finally, the value attribute contains an expression that will be provided by the Hello managed bean.

    The web page connects to the Hello managed bean through the Expression Language (EL) value expression #{hello.name}, which retrieves the value of the name property from the managed bean. Note the use of hello to reference the managed bean Hello. If no name is specified in the @Named annotation of the managed bean, the managed bean is always accessed with the first letter of the class name in lowercase.

    The Submit commandButton element specifies the action as response, meaning that when the button is clicked, the response.xhtml page is displayed.

  5. Double-click the response.xhtml file to view it.

    The response page appears. Even simpler than the greeting page, the response page contains a graphic image, a header that displays the expression provided by the managed bean, and a single button whose action element transfers you back to the index.xhtml page:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html lang="en"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://xmlns.jcp.org/jsf/html">
        <h:head>
            <title>Facelets Hello Response</title>
        </h:head>
        <h:body>
            <h:form>
                <h:graphicImage url="#{resource['images:duke.waving.gif']}"
                                alt="Duke waving his hand"/>
                <h2>Hello, #{hello.name}!</h2>
                <p></p>
                <h:commandButton id="back" value="Back" action="index" />
            </h:form>
        </h:body>
    </html>
  6. Expand the Source Packages node, then the javaeetutorial.hello1 node.
  7. Double-click the Hello.java file to view it.

    The Hello class, called a managed bean class, provides getter and setter methods for the name property used in the Facelets page expressions. By default, the expression language refers to the class name, with the first letter in lowercase (hello.name).

    package javaeetutorial.hello1;
    
    import javax.enterprise.context.RequestScoped;
    import javax.inject.Named;
    
    @Named
    @RequestScoped
    public class Hello {
        private String name;
    
        public Hello() {
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String user_name) {
            this.name = user_name;
        }
    }

    If you use the default name for the bean class, you can specify @Model as the annotation instead of having to specify both @Named and @RequestScoped. The @Model annotation is called a stereotype, a term for an annotation that encapsulates other annotations. It is described later in Section 25.8, “Using Stereotypes in CDI Applications.” Some examples will use @Model where it is appropriate.

  8. Under the Web Pages node, expand the WEB-INF node and double-click the web.xml file to view it.

    The web.xml file contains several elements that are required for a Facelets application. All of the following are created automatically when you use NetBeans IDE to create an application.

    • A context parameter specifying the project stage:

      <context-param>
          <param-name>javax.faces.PROJECT_STAGE</param-name>
          <param-value>Development</param-value>
      </context-param>

      A context parameter provides configuration information needed by a web application. An application can define its own context parameters. In addition, JavaServer Faces technology and Java Servlet technology define context parameters that an application can use.

    • A servlet element and its servlet-mapping element specifying the FacesServlet. All files with the .xhtml suffix will be matched:

      <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>*.xhtml</url-pattern>
      </servlet-mapping>
    • A welcome-file-list element specifying the location of the landing page:

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

6.3.1.1 Introduction to Scopes

In the Hello.java class, the annotations javax.inject.Named and javax.enterprise.context.RequestScoped identify the class as a managed bean using request scope. Scope defines how application data persists and is shared.

The most commonly used scopes in JavaServer Faces applications are the following:

  • Request (@RequestScoped): Request scope persists during a single HTTP request in a web application. In an application like hello1, in which the application consists of a single request and response, the bean uses request scope.
  • Session (@SessionScoped): Session scope persists across multiple HTTP requests in a web application. When an application consists of multiple requests and responses where data needs to be maintained, beans use session scope.
  • Application (@ApplicationScoped): Application scope persists across all users’ interactions with a web application.

For more information on scopes in JavaServer Faces technology, see Section 16.1.1, “Using Managed Bean Scopes.”

6.3.2 Packaging and Deploying the hello1 Web Module

A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You can package a web module into a WAR file by using Maven or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Maven to build, package, and deploy the hello1 sample application.

You can deploy a WAR file to GlassFish Server by:

  • Using NetBeans IDE
  • Using the asadmin command
  • Using the Administration Console
  • Copying the WAR file into the domain-dir/autodeploy/ directory

Throughout the tutorial, you will use NetBeans IDE or Maven for packaging and deploying.

6.3.2.1 To Build and Package the hello1 Web Module Using NetBeans IDE

  1. Start GlassFish Server as described in Section 2.2.1, “To Start GlassFish Server Using NetBeans IDE,” if you have not already done so.
  2. From the File menu, choose Open Project.
  3. In the Open Project dialog box, navigate to:

    tut-install/examples/web/jsf
  4. Select the hello1 folder.
  5. Click Open Project.
  6. In the Projects tab, right-click the hello1 project and select Build. This command deploys the project to the server.

6.3.2.2 To Build and Package the hello1 Web Module Using Maven

  1. Start GlassFish Server as described in Section 2.2.3, “To Start GlassFish Server Using the Command Line,” if you have not already done so.
  2. In a terminal window, go to:

    tut-install/examples/web/jsf/hello1/
  3. Enter the following command:

    mvn install

    This command spawns any necessary compilations and creates the WAR file in tut-install/examples/web/jsf/hello1/target/. It then deploys the project to the server.

6.3.3 Viewing Deployed Web Modules

GlassFish Server provides two ways to view the deployed web modules: the Administration Console and the asadmin command. You can also use NetBeans IDE to view deployed modules.

6.3.3.1 To View Deployed Web Modules Using the Administration Console

  1. Open the URL http://localhost:4848/ in a browser.
  2. Select the Applications node.

The deployed web modules appear in the Deployed Applications table.

6.3.3.2 To View Deployed Web Modules Using the asadmin Command

Enter the following command:

asadmin list-applications

6.3.3.3 To View Deployed Web Modules Using NetBeans IDE

  1. In the Services tab, expand the Servers node, then expand the GlassFish Server node.
  2. Expand the Applications node to view the deployed modules.

6.3.4 Running the Deployed hello1 Web Module

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello1.

  1. Open a web browser.
  2. Enter the following URL:

    http://localhost:8080/hello1/
  3. In the field, enter your name and click Submit.

    The response page displays the name you submitted. Click Back to try again.

6.3.4.1 Dynamic Reloading of Deployed Modules

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed pages or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload takes place, the sessions at that time become invalid, and the client must restart the session.

In GlassFish Server, dynamic reloading is enabled by default.

6.3.5 Undeploying the hello1 Web Module

You can undeploy web modules and other types of enterprise applications by using either NetBeans IDE or the asadmin command.

6.3.5.1 To Undeploy the hello1 Web Module Using NetBeans IDE

  1. In the Services tab, expand the Servers node, then expand the GlassFish Server node.
  2. Expand the Applications node.
  3. Right-click the hello1 module and select Undeploy.
  4. To delete the class files and other build artifacts, go back to the Projects tab, right-click the project, and select Clean.

6.3.5.2 To Undeploy the hello1 Web Module Using the asadmin Command

  1. In a terminal window, go to:

    tut-install/examples/web/jsf/hello1/
  2. Enter the following command:

    mvn cargo:undeploy
  3. To delete the class files and other build artifacts, enter the following command:

    mvn clean

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020