DocsWebLogicWebApp

Creating a Web Application Using WebLogic

This document is a draft version.

Contents


Requirements for This tutorial

You need the following software:

  • NetBeans IDE 6.9
  • Oracle WebLogic Server
  • Java DB or MySQL

This tutorial uses a database named sample that contains tables that the IDE will use to generate files.

Setting up the Oracle WebLogic Server

Downloading and Installing the Server

In this tutorial you will use Oracle WebLogic Server 11gR1 (10.3.3).

  1. Download the installer from the Oracle WebLogic Server Downloads page.
  2. Install the server and create a domain by following the steps in the Oracle WebLogic Server installation guide.

Registering the Server with the IDE

  1. Open the Services window
  2. Right-click the Servers node and choose Add Server.
  3. Select Oracle WebLogic Server from the list. Click Next.
  4. Click Browse and locate the installation of the server.

The default location of the server is the Middleware/wlserver_10.3 directory in your HOME directory.

  1. Type a username and password for the domain. Click Finish.

When you click Finish, the Oracle WebLogic Server will appear under the Servers node in the Services window.

You can right-click the WebLogic server node to perform various actions, including the following:

  • Start and Stop the server
  • Open the Admin Console in your browser
  • View the Server Log in the Output window of the IDE

The Properties window of the server does not contain much information, ie, the address, username or password, compared to GlassFish.

Opening the Admin Console

  1. Right-click the Oracle WebLogic Server node in the Services window and choose Start.

When you start the server you can see the server log in the Oracle WebLogic Server tab of the Output window. You can right-click the Oracle WebLogic Server node and choose View Server Log if the tab is not visible.

  1. Right-click the Oracle WebLogic Server node and choose View Admin Console.

When you choose View Admin Console, the login screen of the server opens in your browser.

  1. Login with the username and password that you specified when you installed the server.

Setting the Default Persistence Provider

In this application you will use Toplink as the persistence provider. The WebLogic server supports Toplink, but the default persistence provider is Kodo. In this exercise you will change the default persistence provider to Toplink in the Admin Console of the WebLogic server.

  1. Click Domain under the Domain Configuration heading.
  2. Click the JPA tab under the Configuration tab.
  3. Select Toplink in the Default JPA Provider dropdown list. Click Save.

This application will use Java Transaction API (JTA) to manage transactions. JTA is enabled by default when you install WebLogic. You can modify the JTA settings in the JTA tab in the Configurations tab for the domain.

Creating the Web Application

Creating the Project

In this tutorial you will create a Java EE 5 web application. The WebLogic server is a Java EE container that fully supports Java EE 5, but the current version does not fully support all features of Java EE 6. When you specify the WebLogic server in the New Project wizard, the wizard allows you to choose either Java EE 5 or J2EE 1.4. You cannot select Java EE 6 if the target server is WebLogic.

  1. Choose File > New Project (Ctrl-Shift-N).
  2. Select Web Application from the Java Web category. Click Next.
  3. Type CustomerBook for the project name and set the project location.
  4. Deselect the Use Dedicated Folder option, if selected.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users or projects. Click Next.

  1. Select the Oracle WebLogic Server from the Server dropdown list.
  2. Select Java EE 5 as the Java EE Version. Click Finish.

Summary

In this exercise you created a Java EE 5 web application project that will contain the entity classes and servlet.


Creating the Database Connection

In this tutorial you will use a MySQL database. In this exercise you will create a database connection that will be used by the wizards in the IDE to generate files. After you create a database connection, the IDE can connect to the database to retrieve details based on the database schema. The IDE also uses the details from the database connection to generate the XML file that the WebLogic server uses to create the data sources on the server and identify the appropriate drivers.

  1. Right-click the MySQL Server node in the Service window and choose Connect.
  2. Type the user and password. Click OK.
  3. Expand the MySQL server node and right-click the sample database and choose Connect.

When you click Connect, a database connection node for the database appears under the Databases node. You can expand the node to view the database tables.

For more details see Connecting to a MySQL Database.

Creating the Persistence Unit

To manage persistence in the application you only need to create a persistence unit, specify which data source and entity manager to use, and then let the container do the work of managing entities and persistence. The container discovers the entity beans at runtime.

You create a persistence unit by defining it in persistence.xml. The project does not contain a persistence.xml yet so you need to create it. In this exercise you will use the New Persistence Unit wizard to create the persistence.xml file. The wizard will help you define the properties of the persistence unit.

You can also create a persistence unit in the New Entity Class wizard. When creating an entity class, the wizard will prompt you to create a persistence unit if one does not exist.

You will now create a persistence unit and specify Toplink as the persistence provider.

  1. Choose New File (Ctrl-N) to open the New File wizard.
  2. From the Persistence category, select Persistence Unit and click Next.
  3. Leave the default name for the persistence unit suggested by the wizard.
  4. Choose TopLink in the Persistence Provider drop-down list.

The default provider is the TopLink Essential.jar. TopLink Essential.jar contains the libraries for Java Persistence. Our entity manager is located in TopLink Essential.jar.

  1. Choose New Data Source in the Data Source dropdown list.
  2. Type jdbc/mysql-sample for the JNDI name.
  3. Choose the mysql sample database connection. Click OK.
  4. Click Finish.


When you click Finish, persistence.xml is created for your project and opens in the editor. You can click XML in the toolbar of the editor to see the XML view of persistence.xml. This file contains all the information the server needs to manage the entities and persistence of the application.

Creating the Entity Classes

You will now use the Entity Classes from Database wizard to create the entity classes based on the relational database.

  1. Choose New File (Ctrl-N) to open the New File wizard. Select Entity Classes from Database from the Persistence category and click Next.
  2. In the Entity Classes from Database wizard, select the jdbc/mysql-sample data source for our database from the Data Source drop-down list and supply the password if necessary.
  3. Select the customer table from the Available Tables and click Add. Click Next.

The wizard displays the selected table and any related tables. The wizard also displays the entity classes that will be created based on the selected tables.

  1. Type ejb as the package for the generated classes. Click Finish.

Creating a Servlet

You now need to add a servlet to the web application. Instead of adding resource creation and lookup code to the servlet, with Java EE 5 you can use resource injection to move that work to the container. You can use annotations to inject resources directly into the servlet, and the container will manage the creation and lookup of the requested resource. In this case, you want to use an entity manager as specified in the persistence unit.

  1. Right-click the project node in the Projects window and choose New > Servlet.
  2. In the New Servlet wizard, name the servlet CustomerDetails and put the servlet into a package named web. Click Finish. When you click Finish, CustomerDetails.java opens in the Source Editor.
  3. In the source editor, right-click in CustomerDetails.java and choose Persistence > Use Entity Manager to inject the PersistenceContext in the class. The IDE adds the following annotation that specifies the persistence unit used by the servlet. The annotation is added above the class declaration.
@PersistenceContext(name = "persistence/LogicalName", unitName = "CustomerBookPU")

The IDE also adds the following annotation injecting a resource for managing transaction boundaries:

        @Resource
        private javax.transaction.UserTransaction utx;

If you expand the editor fold you can see that the IDE adds the following default persist method code to the servlet:

        public void persist(Object object) {
            try {
                Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
                utx.begin();
                EntityManager em =  (EntityManager) ctx.lookup("persistence/LogicalName");
                em.persist(object);    
                utx.commit();
            } catch(Exception e) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE,"exception caught", e);
                throw new RuntimeException(e);
            }
        }

This code looks up the persistence unit defined by @PersistenceContext and an instance of the entity manager.

  1. In CustomerDetails.java, modify the generated persist method shown above to refer to the entity object. When you are finished, the modified code should look like the following.
        public Customer findByID(Integer customerNr) {
              Customer customer = null;
              try {
                  Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
                  utx.begin();
                  EntityManager em =  (EntityManager) ctx.lookup("persistence/LogicalName");
                  customer = em.find(Customer.class, customerNr);
                  utx.commit();
              } catch(Exception e) {
                  Logger.getLogger(getClass().getName()).log(Level.SEVERE,"exception caught", e);
                  throw new RuntimeException(e);
              }
              return customer;
          }
  1. Uncomment the code in the processRequest method and add the following code in bold:
          protected void processRequest(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
              response.setContentType("text/html;charset=UTF-8");
              PrintWriter out = response.getWriter();
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Servlet CustomerDetails</title>");
              out.println("</head>");
              out.println("<body>");
              out.println("<h1>Search Customer Information</h1>");
              String customerNr = request.getParameter("customer_nr");
              if((customerNr != null) && !(customerNr.equals(""))) {

                  Customer customer = findByID(new Integer(customerNr));
                  if(customer != null){
                      out.println("Customer's info for nr. " + customerNr + ": " + customer.getName());
                  }else{
                      out.println("Customer not found.");
                  }
              }
              out.println("<form>");
              out.println("Customer number: <input type='text' name='customer_nr' />");
              out.println("<input type=submit value=Select />");
              out.println("</form>");        
              out.println("</body>");
              out.println("</html>");
              out.close();
          }
  1. Press Ctrl-Shift-I to generate any missing import statements. (The servlet requires an import statement for the Customer entity class.)

Running the Project

  1. In the Projects window, right-click the CustomerBook project node and choose Properties. In the Run panel of the Project Properties dialog box, type /CustomerDetails in the Relative URL field and click OK.
  2. Right-click the project node and choose Run. The IDE starts the application server, builds the project, and opens the CustomerDetails page http://localhost:7001/CustomerBook/CustomerDetails in your browser.

When you click Run, the IDE builds the project and deploys the WAR archive to the WebLogic server.

If you log in to the Admin Console, you can see the deployed WAR by clicking Deployments under Your Deployed Resources. You can see that the table lists the web application and the jdbc/mysql-sample JDBC configuration. You can click the JDBC configuration to view details about the deployed data source. The Connection Pool tab displays details about the pool that is used by the data source, such as the URL of the database, the driver, and the login and password.


  1. Enter an ID number (for example, "1") in the Customer number field and click Submit. The servlet shows you the name of the customer with that ID number.


java.lang.RuntimeException: Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Transaction BEA1-0000F17E9E333057A4BD not active anymore. tx status = Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 36 seconds BEA1-0000F17E9E333057A4BD] Error Code: 0 Call: SQLCall(SELECT customer_id, state, phone, name, fax, addressline2, email, credit_limit, city, addressline1, zip, discount_code FROM customer WHERE (customer_id = ?)) Query: ReadObjectQuery(ejb.Customer)


Implementing Support for JavaServer Faces

In this section you will add support for JavaServer Faces (JSF) to the application. You will first activate support for JSF on the WebLogic Server. After activating the JSF libraries, you can add support for the framework to the project and modify the project's weblogic.xml descriptor file to reference the JSF libraries.

Enabling JavaServer Faces on the Server

The Oracle WebLogic Server includes the libraries necessary for using JSF 1.2 and JSF 2.0 in your applications, but you need to register and enable the libraries in the Admin Console before you can start using them. You only need to enable the libraries once.

  1. Right-click the Oracle WebLogic Server node in the Services window and choose View Admin Console.
  2. Log in to the Admin Console in your browser.
  3. Click Deployments under Your Deployed Resources.
  4. Click Install in the Deployments table.
  5. Navigate to the wlserver_10.3/common/deployable-libraries directory for the Current Location.
  6. Select jsf-2.0.war from the list of libraries in deployable-libraries. Click Next.
  7. Confirm that Install this deployment as a library is selected. Click Next.
  8. Keep the default settings. Click Next.
  9. Confirm that Yes, take me to the deployment's configuration screen. is selected. Click Finish.
  10. In the Overview tab of the Settings page, change the value of the Deployment Order to 99. Click Save.
  11. Navigate to the Deployments table again and confirm that the Library is active.

The JSF 2.0 library is now enabled on the server and available to any applications that you deploy to the server. In the next exercise you will enable JSF in the project.

Enabling JavaServer Faces in the Project

When you created the project, you did not add support for JSF to the project in the New Project wizard because the libraries were not activated on the server. Now that the JSF libraries are activated you can add support for the JSF framework to the project in the project's Properties window.


  1. Right-click the project node and choose Properties.
  2. Select the Frameworks category and click Add to open the Add a Framework dialog.
  3. Select JavaServer Faces and click OK.
  4. Select Registered Libraries and select JSF 2.0 from the drop-down list. click OK.

The IDE adds the JSF 2.0 Libraries to the project under the Libraries node.

After activating the JSF libraries on the server, you can enable JSF directly in the Frameworks pane of the New Project wizard when you create projects.

Modifying the weblogic.xml Descriptor File

  1. Expand the Configuration Files node and open weblogic.xml in the editor.
  2. Modify the XML file to specify the JSF library.
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-web-app.xsd">
  <context-root>/WebApplication3-wl</context-root>
  <library-ref>
      <library-name>jsf</library-name>
      <specification-version>2.0</specification-version>
      <implementation-version>1.0.0.0_2-0-2</implementation-version>
      <exact-match>true</exact-match>
  </library-ref>
</weblogic-web-app>

Generating JSF Pages

  1. Right-click the project node and choose New > Other.
  2. Select JSF Pages from Entity Classes in the JavaServer Faces category of the New File wizard.
  3. Click Add All to create JSF pages for all the available entities. Click Next.
  4. Type web in the JPA Controller Package and JSF Classes Package fields. Click Finish.

Running the Project

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo