| Java EE 7 SDK |
This example application demonstrates the use and injection of request-scoped and session-scoped CDI beans in a web application. The example shows how to implement a simple user authentication scheme.
The demo uses a log-in servlet to authenticate a user with
a username and password. The username and password values
are saved in a request-scoped Credentials bean. The session-scoped
LoginHandler bean checks the credentials provided in the
current request.
The code snippet below shows how to decorate the Credentials and
LoginHandler beans with the RequestScoped and
SessionScoped annotations to indicate to the CDI runtime that
these beans are request-scoped and session-scoped respectively.
The CDI runtime automatically manages the lifecycle of these beans. For example,
a request-scoped Credentials bean can be injected into a
session-scoped LoginHandler bean, and the CDI runtime ensures that
the right request-scoped state is available inside the session-scoped bean.
@RequestScoped
public class Credentials {...}
@SessionScoped
public class LoginHandler implements Serializable {
// Get the request scoped Credentials associated
// with this user.
@Inject Credentials credentials;
}
The LoginServlet servlet obtains the request-scoped
Credentials bean and the session-scoped LoginHandler
bean using field-based injection as shown in the code snippet below.
In the service method, the servlet populates the Credentials
bean with the values from the form and invokes a log-in method on the
LoginHandler bean to handle the authentication.
@WebServlet(name="LoginServlet",urlPatterns={"/LoginServlet"})
public class LoginServlet extends HttpServlet {
// Inject the Credentials request-scoped bean.
@Inject Credentials credentials;
// Inject the Login session-scoped bean.
@Inject LoginHandler login;
}
Perform the following steps to build, deploy, and run the application:
app_dir is the sample application base directory: samples_install_dir/javaee7/cdi/cdi-servlet.app_dir.run outcome.
mvn clean verify cargo:run
clean outcome to undeploy the sample application and to remove the temporary directories such as build and dist.
mvn clean
If you have problems when running the application, refer to the troubleshooting document.
Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.