Handling Forms in Java EE 6 by Using Servlets and CDI

advertisement
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 type-safe. 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 signup 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
o
Download and install the Java Platform, Enterprise Edition 6 (Java EE 6) software development kit
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.
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/compatibility-jsp136984.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 have:
o
o
Knowledge of the Java 7 programming language.
Basic knowledge of Java EE6, specifically servlets and JSP.
o
Basic knowledge of HTML and HTML forms.
This section gives a brief introduction to Contexts and Dependency Injection.
What is Contexts 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 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
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <!DOCTYPE html>
3 <html>
4
<head>
5
<title>Welcome</title>
6
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
7
</head>
8
<body>
9
<h1>Sign-up</h1>
10
11
<p>Please fill in the form to sign up for the Java EE 6
Development forum.</p>
12
<form action="RegisterServlet" method="POST">
13
<label>Name: </label><input type="text" name="name"><br
/>
14
<label>Email: </label><input type="email"
name="email"><br />
15
<label>Password: </label><input type="password"
name="password"><br />
16
<label>How did you learn about this tutorial?</label>
17
<select name="reference">
18
<option value="OLL">Oracle Learning Library</option>
19
<option value="Newsletter">Newsletter</option>
20
<option value="Social">Social network(s)</option>
21
<option value="Search">Internet search</option>
22
<option value="Other">Other</option>
23
</select><br>
24
<label>Gender:</label><br>
25
<input type="radio" name="gender" value="male">Male
26
<input type="radio" name="gender"
value="female">Female<br>
27
<label>Select the topics that you're interested
about:</label><br>
28
<input type="checkbox" name="interests"
value="client">Client-side development
29
<input type="checkbox" name="interests"
value="server">Server-side development
30
<input type="checkbox" name="interests"
value="database">Database technologies
31
<input type="checkbox" name="interests"
value="other">Other<br>
32
<input type="submit" value="Sign-up">
33
</form>
34
35
</body>
36 </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
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <!DOCTYPE html>
3 <html>
4
<head>
5
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
6
<title>Welcome to the Java EE 6 Development Forum</title>
7
</head>
8
<body>
9
<h1>Java EE 6 Development Forum</h1>
10
<a href="signup.jsp">Sign-up!</a>
11
</body>
12 </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
1 package com.example.model;
2
3 public class User {
4
private static String name;
5
private static String email;
6
private static String password;
7
private static String reference;
8
private static String gender;
9
private static String[] interests;
10
11
public User(String name, String email, String password,
String reference,
12
String gender, String[] interests) {
13
this.name = name;
14
this.email = email;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 }
46
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.
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
1 package com.example.cdi;
2
3 public interface UserSession {
4
String welcomeUser(String name);
5 }
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
1 package com.example.cdi;
2
3 public class UserSessionImpl implements UserSession {
4
public String welcomeUser (String name){
5
return "Welcome to the Java EE6 forum, " + name + "!";
6
}
7 }
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
1 package com.example.servlets;
2
3 import com.example.cdi.UserSession;
4 import com.example.model.User;
5 import java.io.IOException;
6 import java.io.PrintWriter;
7 import javax.servlet.ServletException;
8 import javax.servlet.annotation.WebServlet;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 @WebServlet(name = "SignupServlet", urlPatterns =
{"/welcome"})
14 public class SignupServlet extends HttpServlet {
15
16
protected void processRequest(HttpServletRequest
request, HttpServletResponse response)
17
throws ServletException, IOException {
18
response.setContentType("text/html;charset=UTF8");
19
PrintWriter out = response.getWriter();
20
21
String name = request.getParameter("name");
22
String email = request.getParameter("email");
23
String password =
request.getParameter("password");
24
String reference =
request.getParameter("reference");
25
String gender = request.getParameter("gender");
26
String[] interests =
request.getParameterValues("interests");
27
User user = new User(name, email, password,
reference, gender, interests);
28
29
try {
30
31
out.println("<html>");
32
out.println("<head>");
33
out.println("<title>Java EE 6 Development
Forum</title>");
34
out.println("</head>");
35
out.println("<body>");
36
out.println("<h1>The Java EE 6 Development
Forum <h1>");
37
out.println("</body>");
38
out.println("</html>");
39
} finally {
40
out.close();
41
}
42
}
43 }
Select File > Save to save the file.
Exposing the Welcome Method by Using Injection
In this section, you expose the UserSessionImpl service by using injection.
Open the SignupServlet.java file.
Add the following code:
SignupServlet.java: Injecting the UserSession object by Using CDI
Annotations
1 @Inject
2 private UserSession session;
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
1 out.println("<p>" + session.welcomeUser(name) +
"</p>");
Select File > Save to save the file.
Testing the Injection
Right-click the CdiForms project and click Run.
The register page opens in a new window.
Click the Sign-up! link.
Complete the form and click Sign-up.
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:






The Java EE 6 Tutorial chapter on CDI
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
Help OLL About Oracle Contact Us Terms of Use
Download