Handling Forms in Java EE 6 by Using Servlets and CDI

 

Overview

    Purpose

    This tutorial shows you how to handle HTML5 form elements by using servlets and Contexts and Dependency Injection (CDI).

    Time to Complete

    Approximately 1 hour

    Introduction

    Contexts and Dependency Injection (CDI) is a new feature in Java EE 6 that defines a powerful and type-safe Dependency Injection using “contextual” references or scopes. Based on the JSR-299 specification, CDI supplies a set of services that allow Java EE components (such as EJB session beans and JavaServer Faces managed beans) to be bound to lifecycle contexts. These components can then be injected and interact in a loosely coupled way by firing and observing events. The contextual nature of CDI allows the use of beans from different scopes to be more natural and convenient.

    Scenario

    In this tutorial, you create a basic injection scenario using Contexts and Dependency Injection for Java EE 6. To accomplish this, you first learn how CDI works. Later on, you develop a sign-up form for a fictitious forum, process the form by using servlets, and store the sign-up information in a Java bean. Finally, you use CDI to inject the bean and welcome the user to the forum.

    Software Requirements

    The following is a list of software requirements needed to accomplish this tutorial:

    Prerequisites

    Before starting this tutorial, you should have:

    • Knowledge of the Java programming language.
    • Basic knowledge of Java EE 6, specifically servlets and JSP.
    • Basic knowledge of HTML and HTML forms.
 

Introduction to CDI for the Java EE 6 Platform

    This section gives a brief introduction to Contexts and Dependency Injection.

    Dependency Injection refers to the process of supplying an external dependency to a software component, allowing you to remove hard-coded dependencies. By using CDI in Java EE 6, you can inject these external dependencies in a type-safe way and choose which implementation of a particular interface to use.

    CDI also introduces the concept of “contexts”, meaning that injected components (such as Java beans), live in well-defined references or scopes. This feature of CDI also makes the use of beans from different scopes more natural and convenient, since you can mix and match scopes and inject beans from different scopes. CDI is also integrated with Expression Language (EL), which allows any component to be used directly within a JavaServer Faces page or a JavaServer Pages page.

    Another practical advantage of using CDI resides in that it helps you design and build loosely coupled systems, since it essentially decouples the server and the client by means of well-defined types and qualifiers, allowing server implementation to vary. CDI also decouples the lifecycle of components by making components contextual and allowing stateful components to interact by passing messages. Finally, CDI decouples message producers from consumers by means of events.

    By using CDI in your development, any bean can be bound to a lifecycle context, can be injected, and can interact with other beans in a loosely coupled way by firing and observing events. In addition, a bean may be called directly from Java code or it may be invoked in a unified EL expression.

 

Creating a Java EE 6 Web Project

    In this section, you create a Java EE 6 web application on which you’ll build the sign-up form on.

    Open the NetBeans IDE.

    From the File menu, choose New Project.

    Select Java Web from Categories and Web Application from Projects and click Next.

    Enter CdiForms as the project name and click Next.

    Select Oracle WebLogic Server from the Server list.

    Select the Enable Contexts and Dependency Injection check box.

    Enter CdiForms as the context path and click Next.

    Under Frameworks, leave all options blank, and click Finish.

    A new project called CdiForms is created. The index.jsp file appears in the Source pane.

    Right-click the CdiForms project and select Run to test your application.

    A browser window opens and displays a Hello World! message. You successfully created a Java EE 6 web application by using NetBeans.

 

Creating a Sign-up Form with HTML5

    In this section you create an HTML5 form that allows users to sign-up for the Java EE 6 Development forum.

    Select File > New File.

    Select Web from Categories and JSP from File Types and click Next.

    Enter signup as the file name and click Finish.

    The signup.jsp file is created and appears in the Source pane.

    Add the following code to the signup.jsp file:

     

    signup.jsp

       <%@page contentType="text/html" pageEncoding="UTF-8"%>
       <!DOCTYPE html>
       <html>
         <head>
           <title>Welcome</title>
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         </head>
         <body>
           <h1>Sign-up</h1>
      
           <p>Please fill in the form to sign-up for the Java EE 6 Development forum.</p>
           <form action="RegisterServlet" method="POST">
             <label>Name: </label><input type="text" name="name"><br />
             <label>Email: </label><input type="email" name="email"><br />
             <label>Password: </label><input type="password" name="password"><br />
             <label>How did you learn about this tutorial?</label>
             <select name="reference">
                 <option value="OLL">Oracle Learning Library</option>
                 <option value="Newsletter">Newsletter</option>
                 <option value="Social">Social network(s)</option>
                 <option value="Search">Internet search</option>
                 <option value="Other">Other</option>
             </select><br>
             <label>Gender:</label><br>
               <input type="radio" name="gender" value="male">Male
               <input type="radio" name="gender" value="female">Female<br>
             <label>Select the topics that you're interested about:</label><br>
               <input type="checkbox" name="interests" value="client">Client-side development
               <input type="checkbox" name="interests" value="server">Server-side development
               <input type="checkbox" name="interests" value="database">Database technologies
               <input type="checkbox" name="interests" value="other">Other<br>
             <input type="submit" value="Sign-up">
           </form>
           
         </body>
       </html>
      

    Click File > Save to save the changes.

    You successfully created the sign-up form for the Java EE 6 Development forum.

    Open the index.jsp file and add the following code:

     

    index.jsp

      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <!DOCTYPE html>
      <html>
         <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Welcome to the Java EE 6 Development Forum</title>
         </head>
         <body>
            <h1>Java EE 6 Development Forum</h1>
            <a href="signup.jsp">Sign-up!</a>
         </body>
      </html>
      
      

    You successfully added a link from the index.jsp file to the signup.jsp file.

 

Creating the User Object

    In this section, you create a JavaBeans for storing, manipulating, and exposing messages.

    Select File > New File.

    Select Java from Categories and Java Class from File Types and click Next.

    Enter User as the class name.

    Enter com.example.model as the package and click Finish.

    The User.java class is added to the project.

    Open the User.java file and add the following code:

     

    User.java

       package com.example.model;
       
       public class User {
           private static String name;
           private static String email;
           private static String password;
           private static String reference;
           private static String gender;
           private static String[] interests;
           
           public User(String name, String email, String password, String reference, 
                 String gender, String[] interests) {
               this.name = name;
               this.email = email;
               this.password = password;
               this.reference = reference;
               this.gender = gender;
               this.interests = interests;
           }
       
           public static String getName() {
             return name;
           }
           
           public static String getEmail() {
             return email;
           }
       
           public static String getPassword() {
             return password;
           }
       
           public static String getReference() {
               return reference;
           }
       
           public String getGender(){
               return gender;
           }
       
           public String[] getInterests() {
               return interests;
           }
       
      }
       
      

    Select File > Save to save the file.

    You successfully created the User object.

 

Creating the User Session Interface

    In this section, you create a Java interface to allow other components to access functionalities in a standard way. This interface provides a transport for accessing the User object in a standarized way, allowing you to perform operations on it later on.

    Select File > New File.

    Select Java from Category and Java Interface from File Types and click Next.

    Enter UserSession as the class name.

    Enter com.example.cdi as the package and click Finish.

    The UserSession.java class is added to the project.

    Open the UserSession.java file and add the following code:

     

    UserSession.java

      package com.example.cdi;
      
      public interface UserSession {
          String welcomeUser(String name);
      }
      

    Select File > Save to save the file.

    You successfully created the UserSession object.

 

Creating the User Session Interface Implementation

    In this section, you create a Java class for implementing the functionalities accessed through the UserSession interface.

    Select File > New File.

    Select Java from Category and Java Class from File Types and click Next.

    Enter UserSessionImpl as the class name.

    Enter com.example.cdi as the package and click Finish.

    The UserSessionImpl.java class is added to the project.

    Open the UserSessionImpl.java file and add the following code:

     

    UserSessionImpl.java

      package com.example.cdi;
      
      public class UserSessionImpl implements UserSession {
          public String welcomeUser (String name){
              return "Welcome to the Java EE6 forum, " + name + "!";
          }
      }
      
      

    Select File > Save to save the file.

    You successfully created the UserSessionImpl object.

 

Handling the User Input and Exposing the Welcome Service Through CDI

    In this section, you process the HTML form by using a servlet and you expose the UserSession service by using CDI.

     

    Processing the Form Elements by Using a Servlet

      In this section, you create a Java servlet for processing the HTML form.

      Select File > New File.

      Select Web from Categories and Servlet from File Types and click Next.

      Enter SignupServlet as the class name.

      Enter com.example.servlets as the package.

      Enter SignupServlet as the servlet name.

      Enter /welcome as the URL pattern and click Finish.

      The SignupServlet.java file is added to the project.

      Open the SignupServlet.java file and add the following code:

       

      SignupServlet.java - Creating a Servlet

         package com.example.servlets;
         
         import com.example.cdi.UserSession;
         import com.example.model.User;
         import java.io.IOException;
         import java.io.PrintWriter;
         import javax.servlet.ServletException;
         import javax.servlet.annotation.WebServlet;
         import javax.servlet.http.HttpServlet;
         import javax.servlet.http.HttpServletRequest;
         import javax.servlet.http.HttpServletResponse;
        
         @WebServlet(name = "SignupServlet", urlPatterns = {"/welcome"})
         public class SignupServlet extends HttpServlet {
         
             protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
                 response.setContentType("text/html;charset=UTF-8");
                 PrintWriter out = response.getWriter();
        
                 String name = request.getParameter("name");
                 String email = request.getParameter("email");
                 String password = request.getParameter("password");
                 String reference = request.getParameter("reference");
                 String gender = request.getParameter("gender");
                 String[] interests = request.getParameterValues("interests");
                 User user = new User(name, email, password, reference, gender, interests);
        
                 try {
        
                     out.println("<html>");
                     out.println("<head>");
                     out.println("<title>Java EE 6 Development Forum</title>");            
                     out.println("</head>");
                     out.println("<body>");
                     out.println("<h1>The Java EE 6 Development Forum <h1>");
                     out.println("</body>");
                     out.println("</html>");
                 } finally {            
                     out.close();
                 }
             }
         }
        

      Select File > Save to save the file.

     

    Exposing the Welcome Method by Using Injection

      In this section, you expose the welcomeMethod service by using injecting a UserSession object.

      Open the SignupServlet.java file.

      Add the highlighted code to the SignupServlet.java file:

       

      SignupServlet.java: Injecting the UserSession object by Using CDI Annotations

         package com.example.servlets;
         
         import com.example.cdi.UserSession;
         import com.example.model.User;
         import java.io.IOException;
         import java.io.PrintWriter;
         import javax.servlet.ServletException;
         import javax.servlet.annotation.WebServlet;
         import javax.servlet.http.HttpServlet;
         import javax.servlet.http.HttpServletRequest;
         import javax.servlet.http.HttpServletResponse;
        
         @WebServlet(name = "SignupServlet", urlPatterns = {"/welcome"})
         public class SignupServlet extends HttpServlet {
         
             @Inject  
         private UserSession session; 
        
             protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
                 response.setContentType("text/html;charset=UTF-8");
                 PrintWriter out = response.getWriter();
        
                 String name = request.getParameter("name");
                 String email = request.getParameter("email");
                 String password = request.getParameter("password");
                 String reference = request.getParameter("reference");
                 String gender = request.getParameter("gender");
                 String[] interests = request.getParameterValues("interests");
                 User user = new User(name, email, password, reference, gender, interests);
        
                 try {
        
                     out.println("<html>");
                     out.println("<head>");
                     out.println("<title>Java EE 6 Development Forum</title>");            
                     out.println("</head>");
                     out.println("<body>");
                     out.println("<h1>The Java EE 6 Development Forum <h1>");
                     out.println("</body>");
                     out.println("</html>");
                 } finally {            
                     out.close();
                 }
             }
         }
        

      A UserSesssion object called session was injected.

      Using the previously injected class, add the following code to greet the user:

       

      SignupServlet.java: Calling the welcomeUser Injected Method

        package com.example.servlets;
         
         import com.example.cdi.UserSession;
         import com.example.model.User;
         import java.io.IOException;
         import java.io.PrintWriter;
         import javax.servlet.ServletException;
         import javax.servlet.annotation.WebServlet;
         import javax.servlet.http.HttpServlet;
         import javax.servlet.http.HttpServletRequest;
         import javax.servlet.http.HttpServletResponse;
        
         @WebServlet(name = "SignupServlet", urlPatterns = {"/welcome"})
         public class SignupServlet extends HttpServlet {
         
         
            @Inject  
            private UserSession session;  
            
        
             protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
                 response.setContentType("text/html;charset=UTF-8");
                 PrintWriter out = response.getWriter();
        
                 String name = request.getParameter("name");
                 String email = request.getParameter("email");
                 String password = request.getParameter("password");
                 String reference = request.getParameter("reference");
                 String gender = request.getParameter("gender");
                 String[] interests = request.getParameterValues("interests");
                 User user = new User(name, email, password, reference, gender, interests);
        
                 try {
        
                     out.println("<html>");
                     out.println("<head>");
                     out.println("<title>Java EE 6 Development Forum</title>");            
                     out.println("</head>");
                     out.println("<body>");
                     out.println("<h1>The Java EE 6 Development Forum <h1>");
                     out.println("<p>" + session.welcomeUser(name) + "</p>");    
                     out.println("</body>");
                     out.println("</html>");
                 } finally {            
                     out.close();
                 }
             }
         }
        
        

      Select File > Save to save the file.

     

    Testing the Injection

      Right-click the CdiForms project and click Run.

      The registration page opens in a new window.

      Click the Sign-up! link.

      Complete the form and click Sign-up.

      1. Enter a person's name, such as Nancy Green.
      2. Enter a valid email address, such as ngreen@mail.com.
      3. Enter a password, such as welcome1.
      4. Select an option from the list on how you learned about this tutorial, such as Other.
      5. Enter the person's gender, such as Female.
      6. Select the topics you're interested about, such as Client-side development and Server-side development.

      The welcome page is displayed.

      You successfully injected the welcomeUser method from the UserSessionImpl object!

 

Summary

    In this tutorial you learned about the basics of Contexts and Dependency Injection in the Java EE 6 platform. You also learned how CDI works.

    You also learned how to:

    • Create an HTML5 form
    • Process the form elements by using servlets
    • Inject a basic component into the servlet by using CDI

    Resources

    For more information about the topics in this tutorial, see:

    Credits

    • Lead Curriculum Developer: Miguel Salazar
    • Other Contributors: Eduardo Moranchel, Edgar Martinez