Introduction to Java EE 6 using NetBeans

Java EE is a remarkable technology for all that it can accomplish, but it has been plagued by criticism of being overly complicated and verbose.

Much of this criticism was justified for the fact that Java EE relies heavily on XML-based configuration, requiring many interfaces and exceptions, presenting developers with many hurdles to face when using it. Technologies like Hibernate and Spring emerged, and gained much attraction simply because they sought to address those complexities.

With the introduction of Java EE 5, the core platform once again gained the upper hand, trying the same formula that helped catapult Hibernate and Spring into developers' favor. Annotations were brought in, to tone down the verbosity of the code, along with reduction of checked exceptions, POJO programming, introduction of JSF, enhancements in EJB QL and Application Container, and simplification of Session Beans.

Session Beans are Java objects that perform a multitude of operations but are mainly used for storing data. As with Java EE 5, Session Beans can be either Stateless or Stateful.

  • Stateful Session Beans maintain a conversational state for the entire client session.
  • Stateless Session Beans do not maintain a conversational state. These beans are maintained in memory for as long as the client request takes and after that, the state is no longer kept in memory.

The idea of simplifying development continues in Java EE 6. To start, some of the "fat" Java EE acquired during its lifetime is being burned by pruning some outdated technologies. API's such as JAXR, EJB 2.x Entity Beans, Java EE Application Deployment, and others have been marked as "pruned", either for low usage by developers, or for not being entirely implemented by the vendors that chose to create the Application Containers.

On top of that, performance enhancements for deployment and resources used, such as Java EE Web Profiles, were added so that developers that do not utilize the entire Java EE stack can deploy applications based only on what they use.

Updated API's, such as JAX-RS 1.1, EJB 3.1, JPA 2.0, were also introduced in Java EE 6.

If you wish to know more about the technologies in Java EE 6 visit:

NetBeans is the first IDE to have complete support for Java EE 6.

Here are some of the benefits of using NetBeans with Java EE 6:

The editor houses the JSF components, as follows:

  • Wizards that let the developer create JSF CRUDs. CRUDs is an acronym for Create-Read-Update-Delete, the basic operations for different entities in a web application.
  • Creation of JSF pages from the Entity Classes.
  • Entity relationships are supported straight from NetBeans.
  • Integration with the latest GlassFish Server and more.

Getting ready

Please refer to the recipe Creating a Web Project using the Wizard for project creation and the necessary tools to proceed with this recipe.

How to do it...

We will create a New Project based on Java EE 6 Web. The necessary steps are as follows:

  1. Right-click on the Projects window and select New Project... or press CTRL+SHIFT+N (shortcut).
  2. On New Project window: under Categories, select Java Web and under Projects, select Web Application, then click Next.
  3. Name and Location: under Project Name, write FirstJavaEE6Application, and click Next.
  4. Server and Settings:
    • Server: GlassFish Server 3.1
    • Java EE Version: Java EE 6 Web
    • Context Path: leave the default value
  5. Click Next.
  6. In Frameworks: click Finish.

Upon clicking on the Finish button, NetBeans creates a project structure for us.

The created structure is shown in the following screenshot:

How to do it...

The new project is created under the Projects window and a default JSP file is opened in the editor under the name index.jsp.

We will then proceed by adding a Servlet.

  1. Right-click on FirstJavaEE6Application and select New, and then click on Servlet....
  2. Under Name and Location: under Class Name, write FirstServlet, leave Location pointing to Source Packages and under Package, write servlets and click Finish.

A new Servlet is added to the project structure and the FirstServlet.java file is opened in the editor.

Our next step is to add an Enterprise JavaBean (EJB):

  1. Right-click on FirstJavaEE6Application and select New; then click on Session Bean... or Ctrl+N (shortcut).
  2. Under Categories, select Java EE and under File Types, select Session Bean, then click Next.
  3. Name and Location:
    • under EJB Name, write FirstEJB
    • leave Project and Location with default values
    • under Package, type ejbs
    • Session Type should be marked with Stateless and leave Create Interface unmarked
  4. Click Finish.

This will generate the EJB POJO and the FirstEJB.java will be shown in the editor.

With FirstEJB.java open, let's add some behavior to it:

  1. Right-click inside the body of the class and select Insert Code... or press Alt+Insert (shortcut).
  2. Select Add Business Method....
  3. Under Name, type: reverseString.
  4. In Return type, write String.
  5. Then click on Add and under name, type normalString.
  6. Click OK.
How to do it...

Inside the reverseString method, type:

return new StringBuffer(normalString).reverse().toString();

The whole class will look like this:

How to do it...

We need to call the EJB from within the Servlet. So inside of FirstServlet.java, type:

@EJB FirstEJB firstEJB;

And resolve the import by leaving the cursor on top of the FirstEJB declaration and press Alt+Enter.

How to do it...

Click Add import for ejbs.FirstEJB and the import error is resolved.

Then replace the code inside the try-catch block, the one that is commented out, with:

out.println("<html>");
out.println("<body>");
out.println("<h1>FirstSevlet backwards is "+ firstEJB.reverseString("FirstServlet") +"</h1>");
out.println("</body>");
out.println("</html>");

Click on the Save button.

With all the codes in place, all that is left for us is to run our project.

  1. After saving the FirstServlet.java, right-click on FirstJavaEE6Application and select Run.
  2. When the browser opens showing the contents of index.jsp, replace the URL with http://localhost:8080/FirstJavaEE6Application/FirstServlet

The contents of the web page will then turn to:

FirstServlet backwards is telvreStsriF

How it works...

When the user clicks the Finish button in the Project Creation step, NetBeans creates the project structure and the configuration files necessary for this project to run in the Application Server.

Note that when adding a Servlet, the IDE generates the doGet and doPost methods and adds a method call to the processRequest method. While this is a nice way of forcing all traffic from a servlet to be tunneled in one method, in the real world you might want to change that by being more specific in what is needed from your doGet() or doPost() methods.

Note that an index.jsp file is created and opened, by default, in the code editor.

Our first Session Bean, called FirstEJB, is a Stateless session bean. This means that the Session Bean will not maintain a conversational state for a specific client. When the request is processed by the bean and execution is returned to the servlet, the bean will not hold store any information about the request.

After removing all the comments from FirstEJB, it is noticeable how small that EJB looks.

The reverseString() business method that we have created for our Session Bean returns a reverse string to the client. This method call is used from the Servlet. The Servlet can access the Session Bean, thanks to the Dependency Injection we are performing.

The Dependency Injection code, or simply DI, is:

@EJB FirstEJB firstEJB;

DI is a mechanism employed by Application Servers to instantiate and assign a certain object to the reference used. In our case, GlassFish sees the @EJB annotation before the FirstEJB class name and assigns a new Object of that type to the FirstEJB reference.

The call to the PrintWriter will then output the information as an HTML page, a rather cumbersome way of writing HTML, but enough for our example, and also output the reverseString method call and place the output in the middle of our HTML code.

Java EE 6 Web Profile is a smaller subset of the entire Java EE stack. As mentioned previously, this is very useful when not all API's are needed for a certain project, making it lighter to run and less resource-hungry. This not only makes better use of the resources we have but also makes life less complicated when maintaining a certain application.

There's more...

Let's write some JUnit tests to our EJB's and check the changes that Java EE 6 and GlassFish deploy on Save.

Writing JUnit tests to your EJB

  1. Right-click on FirstEJB.java, select Tools, and then click on Create JUnit Tests.
  2. The Select JUnit Version dialog will pop-up, select JUnit 4.x, and click Select.
  3. The Create Tests dialog is presented; de-select JavaDoc Comments and Source Code Hints under Generated Comments.
    Writing JUnit tests to your EJB
  4. Click OK.

Replace the contents of testReverseString with:

System.out.println("reverseString");
String normalString = "raw";
FirstEJB instance = (FirstEJB)javax.ejb.embeddable. EJBContainer.createEJBContainer().getContext(). lookup("java:global/classes/FirstEJB");
String expResult = "war";
String result = instance.reverseString(normalString);
assertEquals(expResult, result);

Press Shift+F6 to run the JUnit.

The Test Results window will appear with the list of Passed Tests and the Output of GlassFish Server.

Writing JUnit tests to your EJB

The Embeddable EJB Container is a new API in Java EE 6 and can be checked by visiting:

http://jcp.org/aboutJava/communityprocess/final/jsr318/index.html

This API further simplifies the way JUnit tests can be written to test EJBs.

Deployment descriptor is optional when creating servlets

This is yet another new feature in Java EE 6 present in the Servlet 3.0 specification.

The entire configuration which was previously stored in XML is now transferred and implemented with annotations within the Servlet itself.

An example of annotation in our Servlet is:

@WebServlet(name="FirstServlet", urlPatterns={"/FirstServlet"})

Notice that we have not touched any configuration files. If you are new to Java EE world, this will not sound so groundbreaking, but for those with more experience in the field, this is a very good addition to the platform.

Deploy on Save

It is well-known that NetBeans offers a handy integration with GlassFish Server.

One of these features is Deploy on Save. Every time a file, JSP, or servlet for example, is saved on the editor, NetBeans notifies the container and deploys the file for usage.

Although handy, not everyone might want or enjoy this feature. This is mainly because application dependencies might be broken when changes are deployed.

Deploy on Save

To turn this feature off:

  1. Right-click on the Projects name, FirstJavaEE6Application, and select Properties.
  2. Under Categories, click on Run and de-select Deploy in the Save option.
  3. Click OK.

Note that this will force manual deployment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.76.227