Handling Forms in Java EE 6 by Using Servlets and CDI

Topic List Expand All Topics Hide All Images Print

Overview

Purpose

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

Time to Complete

Approximately 1 hour

Introduction

Dependency Injection refers to the process of supplying an external dependency to a software component, making an application architecturally pure. This process aids in the design and testing processes, since because dependencies are "injected" instead of being looked up. These component injections are type-safe. CDI is based on the JSR-299 specification.

Among many other practical advantagesBy of using CDI in your development, you essentially decouple the server and the client, allowing implementation variations; decouple message producers from consumers, by means of events; and eliminate lookup by using string-based names for wiring and correlations; among many other practical advantages.

Scenario

In this tutorial, you first learn what how Contexts and Dependency Injection is and how it works. Later on, you develop a sign-up form for an a fictitious forum. You then learn how to process this the form by using Sservlets. Finally, you use CDI to inject a class that welcomes the user to the forum.

Software Requirements

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

o  Download and install Java Platform, Enterprise Edition 6 (Java EE 6) software development kit (SDK) from http://www.oracle.com/technetwork/java/javaee/downloads/index.html.

o  Download and install NetBeans integrated development environment (IDE) 7.2 from http://www.netbeans.org/downloads/index.html.

o  Download and install Oracle WebLogic Server Zip Distribution from http://www.oracle.com/technetwork/middleware/weblogic/downloads/index.html.

§  This tutorial uses NetBeans IDE 7.2 and WebLogic 12.1.1 as the web server, but you may use any other compliant Java EE web profile compliant server. For more information on about such servers, refer togo to http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html.

§  To install and configure WebLogic Server 12c in NetBeans, refer go to: Installing, Configuring, and Testing WebLogic Server 12c Developer Zip Distribution in NetBeans.

Prerequisites

Before starting this tutorial, you should:

o  Have knowledge of the Java 7 Pprogramming Llanguage.

o  Have basic knowledge of the Java EE 6 Platform, specifically Sservlets and JSP.

o  Have basic knowledge of HTML and HTML forms.

Introduction to Contexts and Dependency InjectionCDI for the Java EE 6 Platform

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

What is Contexts Dependency Injection?

Contexts Dependency InjectionCDI for the Java EE 6 Pplatform introduces a standard set of component management services to the Java EE platform. CDI manages the lifestyle and interactions of stateful components bound to well-defined contexts. CDI It provides typesafe dependency injection between components. CDI is included in the Java EE 6 platform as part of both, the full profile and the web profile.

Creating an Java EE 6 Web Project

In this section, you create a new Java EE 6 web application on which you’ll build the REST API server on.

Open the NetBeans IDE.

From the File menu, choose New Project.

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

Enter CdiForms as the project name and click Next.

Select Oracle WebLogic Server from the Server drop-down menulist.

Check Select the Enable Contexts and Dependency Injection optioncheck box.

Enter CdiForms as the Ccontext Ppath 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 project and select Run to test your application.

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

Creating the a Sign-up Form with HTML5

In this section you will create a RESTful web service by using NetBeans.

Select File > New File.

Select Web Ffrom the Web category Categories, and select JSP from File Types and click Next.

Enter signup as the file name and click Finish.

The signup.jsp file has beenis created and now appears in the Source pane.

Add the highlighted code to the signup.jsp file:

signup.jsp

Click File > Save to save the changes.

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

Creating the User Object

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

Select File > New File.

Select Java Ffrom the Java category Categories, and select Java Class from File Types. and Cclick 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 highlighted 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 successful created Tthe User object has been created.

Creating the User Session Interface

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

Select File > New File.

Select Java from CategoriesFrom the Java category, select and Java Interface from File Types. and Cclick 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 highlighted code:

UserSession.java

package com.example.cdi;

public interface UserSession {

String welcomeUser(String name);

}

Select File > Save to save the file.

You successfully created Tthe UserSession object has been created.

Creating the User Session Interface Implementation

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

Select File > New File.

Select Java from CategoriesFrom the Java category, select and Java Class from File Types. and Cclick 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 highlighted 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 Tthe UserSessionImpl object has been created.

Handling the Form Elements by Using Servlets and CDI

This section gives a brief introduction to RESTful web services and JAX-RS.

Processing the Form Elements by Using a Servlet

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

Select File > New File.

Select Web Ffrom the Web categoryCategories, select and Servlet from File Types. and Cclick Next.

Enter SignupServlet as the Class Nameclass name.

Enter com.example.servlets as the Ppackage.

Enter Signup as the Sservlet name.

Enter signup as the URL Ppattern and click Finish.

The SignupServlet.java file is added to the project.

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

SignupServlet.java

package com.example.servlets;

import com.example.cdi.UserSession;

import com.example.model.User;

import java.io.IOException;

import java.io.PrintWriter;

import javax.inject.Inject;

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 = "RegisterServlet", urlPatterns = {"/RegisterServlet"})

public class RegisterServlet 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("");

out.println("");

out.println("");

out.println("");

out.println("

");

out.println("

Java EE6 Forum

");

out.println("

" + session.welcomeUser(user.getName()) + "

");

out.println("

");

out.println("

");

} finally {

out.close();

}

}

//

/**

* Handles the HTTP

* GET method.

*

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

/**

* Handles the HTTP

* POST method.

*

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

/**

* Returns a short description of the servlet.

*

* @return a String containing servlet description

*/

@Override

public String getServletInfo() {

return "Short description";

}//

}

Select File > Save to save the file.

Injecting the Welcome Method by Using CDI

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

Open the SignupServlet.java file.

To inject the UserSession class, aAdd the following code to inject the UserSession class:

SignupServlet.java

A UserSesssion object called session has beenwas injected.

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

Select File > Save to save the file.

Testing the Injection

Right-click the CDIForms project and click Run.

The sign-up form opens in Aa new browser window opens with the sign-up form page.

Fill Complete the form and click Submit.

You're forwarded to a screen that greets you.The Welcome page is displayed.

Summary

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

You also learned how to:

  1. Create an HTML5 form
  2. Process the form elements by using Sservlets
  3. Inject a basic component into the Sservlet by using CDI
Resources

For more information on about the topics in this tutorial:

  1. The Java EE 6 Tutorial
  2. Oracle blog on Java EE 6 CDI Qualifiers explained
  3. Contexts and Dependency Injection in Java EE 6
  4. JSR 299: Contexts and Dependency Injection for the Java EE platform
  5. Oracle courses and learning paths for Java EE 6.
  6. To learn more about Java EE 6, refer to additional OBEs in the Oracle Learning Library.
Credits
  1. Lead Curriculum Developer: Miguel Salazar
  2. Other Contributors: Eduardo Moranchel, Edgar Martinez

To help navigate this Oracle by Example, note the following:

Hiding Header Buttons:

Click the Title to hide the buttons in the header. To show the buttons again, simply click the Title again.

Topic List Button:

A list of all the topics. Click one of the topics to navigate to that section.

Expand/Collapse All Topics:

To show/hide all the detail for all the sections. By default, all topics are collapsed

Show/Hide All Images:

To show/hide all the screenshots. By default, all images are displayed.

Print:

To print the content. The content currently displayed or hidden will be printed.

To navigate to a particular section in this tutorial, select the topic from the list.

Help OLL About Oracle Contact Us Terms of Use