I've had questions about how to inject Web Beans into servlets and whether that is supported. In this entry I'll outline a method of accomplishing just that.
This is a simple login application that communicates to a servlet using Ajax calls from a JSP view. I'm not going to focus on the view or the protocol (Ajax) that is used to communicate with the servlet. If you are interested in that, you can check out the source (instructions at the end of this post). I'm going to focus on the servlet code and the supporting classes for the application. The application just prompts for a user name / pasword, and pressing the submit button sends those values to a servlet. First, let's take a look at some of the supporting code for the application:
Listing 1: Login Credentials
- Line 11: The name of this Web Bean will be credentials since we don't supply an argument to the Named annotation.
- Line 12: For the purposes of this simple application this Web Bean scope will be for the current request.
- Line 13: Specifies the default qualifier type for this Web Bean. Note that you should not have to specify this if it's the only qualifier type being used. In future implementations of Web Beans this should be fixed.
Listing 2: Login
- Line 13: The name of this Web Bean will be login
- Line 14: This Web Bean will exist for the session
- Line 15: Specifies the default qualifier type for this Web Bean.
- Line 18: We're injecting an instance of Credentials so we can check the validity of the user name and password entries
Listing 3: Login Servlet
- Line 15: New for Servlet 3.0 - eliminates servlet entry in web.xml! Not relevant to this example, but worth mentioning.
- Line 19: The Web Beans Bean Manager can also be injected. The Bean Manager api provides some useful methods for interrogating portions of a Web Beans application.
- Line 22: The Credentials Web Bean is injected making it available to the servlet.
- Line 38: Now we can access the Credentials Web Bean.
- Line 40: We can also use the injected Login Web Bean instance.
This is just one example of Web Bean injection into a servlet. There are more areas in the JavaEE6 platform that can be used as Web Bean injection points - topics that will certainly be covered in future posts. The sample for this blog can be found under the glassfish-samplesproject. You can check out the code following these instructions. Once the workspace is checked out, you can find this sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet. You can find documentation for the sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet/docs. As with all the Web Beans samples now, you should run with GlassFish V3 - any build after September 2 2009.