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 servlets 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, because dependencies are "injected" instead of looked up. These component injections are typesafe. CDI is based on the JSR-299 specification. Among many other practical advantages 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. Scenario In this tutorial, you first learn how Contexts and Dependency Injection works. Later on, you develop a sign-up form for a fictitious forum. You then learn how to process the form by using servlets. 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 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. 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 server. For more information about such servers, go to http://www.oracle.com/technetwork/java/javaee/overview/compatibilityjsp-136984.html. To install and configure WebLogic Server 12c in NetBeans, go to Installing, Configuring, and Testing WebLogic Server 12c Developer Zip Distribution in NetBeans. Prerequisites Before starting this tutorial, you should: o o o Have knowledge of the Java 7 programming language. Have basic knowledge of Java EE 6, specifically servlets and JSP. Have 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. CDI for the Java EE 6 platform introduces a standard set of component management services. CDI manages the lifestyle and interactions of stateful components bound to well-defined contexts. It provides typesafe dependency injection between components. CDI is included in the Java EE 6 platform as part of the full profile and the web profile. Creating a Java EE 6 Web Project In this section, you create a Java EE 6 web application on which you’ll build the REST API server. 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 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 a RESTful web service by using NetBeans. 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 highlighted code to the signup.jsp file: Click File > Save to save the changes. You successfully created the sign-up form for the Java EE 6 Development forum. Creating the User Object In this section, you create a JavaBeans component 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 highlighted code: package com.example.model; public class User { private static String name; private static String email; private private private private static static static static String password; String reference; String gender; 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 the User object. 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 Categories 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 highlighted code: 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 JavaBeans component for storing, manipulating, and exposing messages. Select File > New File. Select Java from Categories 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 highlighted code: 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 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 from Categories and Servlet from File Types and click Next. Enter SignupServlet as the class name. Enter com.example.servlets as the package. Enter Signup as the servlet name. Enter signup 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: package com.example.servlets; import import import import import import import import import import com.example.cdi.UserSession; com.example.model.User; java.io.IOException; java.io.PrintWriter; javax.inject.Inject; javax.servlet.ServletException; javax.servlet.annotation.WebServlet; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; 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. Add the following code to inject the UserSession class: A UserSesssion object called session was injected. Using the previously injected class, add the following code to greet the user: Select File > Save to save the file. Testing the Injection Right-click the CDIForms project and click Run. The sign-up form opens in a new browser window. Complete the form and click Submit. 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. 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: The Java EE 6 Tutorial Oracle blog on Java EE 6 CDI Qualifiers explained Contexts and Dependency Injection in Java EE 6 JSR 299: Contexts and Dependency Injection for the Java EE platform Oracle courses and learning paths for Java EE 6 To learn more about Java EE 6, refer to additional OBEs in the Oracle Learning Library. Credits Lead Curriculum Developer: Miguel Salazar 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