Oracle Application Server Containers for J2EE

As described in Chapter 2, Oracle Application Server 10 g provides a fully J2EE-compliant container called Oracle Application Server Containers for J2EE (OC4J). For development and small-scale installations, Oracle also provides for a separately downloadable standalone version of OC4J including full documentation. After successfully installing OC4J, either as the standalone version or the full version included with Oracle Application Server 10 g , you can develop servlets, JavaServer Pages (JSPs), and Enterprise JavaBeans (EJBs) within the OC4J container.

Note  

As of Oracle9i Database R2, you can no longer develop servlets, JSPs, and EJBs within the Oracle Database.

To verify that OC4J is properly running, open a web browser and set the address to http://localhost:8888. If OC4J is running, you will see a welcome page providing links to OC4J information, documentation, and sample applications. OC4J will be discussed further in 15.

Servlets

Servlets provide a way to create a dynamic HTML or XML response document ”for example, a web page displaying data from an Oracle database ”to an HTTP request. Specifically, servlets are server-side Java programs that run in a J2EE application server such as OC4J.

The first HTTP servers simply responded to HTTP requests by returning static HTML documents. Soon developers realized the enormous opportunity for web-based applications that such a worldwide network of HTTP servers could provide, if only the HTTP servers could execute programs to create dynamic response pages. The Common Gateway Interface (CGI) was one of the first practical solutions for creating dynamic pages, and soon web servers were running Perl programs, shell scripts, and almost any other language to create HTML pages. However, each HTTP request required the web server to spawn a new process in which to run the CGI program. The CGI program relied on environment variables , posted form values, and the request URL to create the response document, and could not interact with the web server once it began execution.

Because of the limited scalability of CGI programs, servlets soon replaced CGI programs as the tool of choice for creating dynamic web pages. Because servlets run as a continuous process within a single thread, they provide state maintenance and a high-performance solution to web-based application development. Because servlets are Java programs running within a JVM, they have access to all of the capabilities included within the J2EE platform, such as JDBC. As with all Java programs, the same servlets can execute in any J2EE-compliant container on any web server without having to recompile the program.

Similar to Java stored procedures, servlets are not standalone applications and do not have a static main() method. Rather, servlets extend one of the two standard servlets base classes, either javax.servlet.GenericServlet or javax.servlet.http.HttpServlet. Instead of having a main() method for the entrance point, the servlet overrides either or both base class methods doGet() to process an HTTP GET request, and doPost() to process an HTTP POST request. Both overridden methods accept two parameters with the following classes:

  • HttpServletRequest The request from the client application, such as a web browser

  • HttpServletResponse The response to return to the client application

The servlet container passes these parameters to the servlet, and once the servlet has completed processing, it passes the response back to the client application.

A servlet example uses an HTML document to send parameters to a servlet using an HTTP GET request. For this example, we will create both the HTML document containing the necessary form and input tags, and the servlet processed by the form action parameter. Using this example, the user enters the month, day, and year of his or her birthday, and the servlet displays the corresponding day of the week.

Create the HTML Document

Create an HTML document containing a form to capture and submit the parameters required by the servlet. Save the HTML tags and text listed below as a file named BirthdayServlet.html in the <j2ee_home>/default-web-app directory. The action tag specifies that the servlet is located in the default web application classes directory whose virtual path is set to /servlet.

 <HTML> <HEAD><TITLE>Birthday Servlet</TITLE></HEAD> <BODY>    <H1>When is your birthday?</H1>    <FORM method="GET" action="/servlet/BirthdayServlet">       Month <INPUT name="MONTH" size="2" type="TEXT"><BR>       Day   <INPUT name="DAY"   size="2" type="TEXT"><BR>       Year  <INPUT name="YEAR   size="4" type="TEXT"><BR>       <INPUT type="SUBMIT">    </FORM> </BODY> </HTML> 

Note that the case of the action parameter of the FORM tag, and the values of the name parameters for the text input parameters, must match this example.

Create the Servlet

The servlet uses classes within the java.text.SimpleDateFormat and the java.util.Calendar J2SE packages to create a dynamic web page. Save the servlet code listed below as BirthdayServlet.java in the <j2ee_home>/default_web_app/WEB-INF/classes directory and compile the source file to BirthdayServlet.class.

Note  

Before compiling the example servlet, make sure the <j2ee_home>/lib/servlet.jar archive is located in your class path.

 // The following three imports are required for all servlets import java.io.*; import java.servlet.*; import java.servlet.http.*; import java.text.SimpleDateFormat; import java.util.Calendar; public class BirthdayServlet extends HttpServlet {    public void doGet(HttpServletRequest  request,                      HttpServletResponse response)          throws ServletException, IOException {       int year, month, day;       Calendar cal = Calendar.getInstance();       SimpleDateFormat sdf = new SimpleDateFormat("EEEE");       // Set the response content MIME type       response.setContentType("text/html");       ServletOutputStream out = response.getOutputStream();       out.println("<HTML">);       out.println("<HEAD><TITLE>Birthday Servlet</TITLE></HEAD>");       out.println("<BODY><H1>");       try {          // For calendars, subtract 1 from the month (0=Jan,11=Dec)          cal.set(Integer.parseInt(request.getParameter("YEAR")),                  Integer.parseInt(request.getParameter("MONTH"))-1,                  Integer.parseInt(request.getParameter("DAY")));          out.print("You were born on a ");          out.println(sdf.format(cal.getTime()));       } catch (NumberFormatException e) {          out.println("Invalid date");       }       out.println("</H1></BODY></HTML>");    } } 

Test the Servlet

After creating the HTML document, and successfully compiling the servlet, you are ready to test creating a dynamic web page. Load the HTML document using the following URL:

 http://localhost:8888/BirthdayServlet.html 

Enter in the values for your birthday. For example, if you were born on January 26, 1967, enter 1 in the Month text box, 26 in the Day text box, and 1967 in the Year text box (without the quotes). Click the Submit button to pass these parameters within the URL to the servlet. You should receive a response HTML document showing:

 You were born on a Thursday 

JavaServer Pages

As shown by this example, servlets require the developer to code both the presentation logic by outputting the HTML tags, plus the business logic, all within the same program. This tight coupling of presentation and business logic is not flexible and is difficult to maintain. The responsibilities for developing the HTML framework might be a person or group using sophisticated web design tools, whereas the responsibilities for developing the business logic is usually a developer or group using an IDE such as JDeveloper. Changes to either the application presentation or the business logic require careful coordination between both parties.

JSPs (see Table 12-6) are a method to separate the HTML tags from the Java code containing the business logic so that the web designers and application developers can each focus on what they do best. A typical JSP file contains a mixture of HTML tags for the static content, and Java code snippets called scriptlets to create the dynamic content. J2EE-compliant web containers include a JSP translator for processing JavaServer Pages files.

Table 12-6: Common JSP Elements

Element

Syntax

Include a file

<%@ include file= ˜relative url %>

Page attributes

<%@ page import= ˜package1,package2,...
session= truefalse
errorPage= ˜relative url
isErrorPage= truefalse
contentType= ˜content type %>

Forward to a new page

<jsp:forward page= ˜relative url
<jsp:param name= name value= value />
</jsp:forward>

Comment

<% “ comment “%>

Declaration

<%! declaration %>

Scriptlet

<% Java code %>

Print a value

<%= variable or expression %>

The JSP translator is fundamentally a servlet precompiler. The JSP translator accepts requests for web pages containing a .jsp extension, and converts the JSP input files into servlets. Upon the first request for a JSP where the corresponding servlet does not yet exist or the JSP source is newer than the previously generated servlet, the container automatically creates and compiles a new servlet into a corresponding class file. You will usually notice slower performance during the translation and compilation time; however, all subsequent requests for the JSP are as fast as calling a servlet.

Within the Java code inside a JSP, there are several implicitly created objects to allow the JSP to access parameters available to servlets. Common implicit objects include request and response that correspond to the two parameters of the doGet() and doPost() servlet methods.

We will re-create the servlet example using a JSP to demonstrate how JSPs reduce coding complexity. You will need to modify the action parameter of the HTML form to call the JSP instead of a servlet, and then code the JSP. Note that this example only provides a brief introduction into the capabilities of JSPs; be sure to read Chapter 14 for a more complete explanation.

Create the HTML Document

Copy the BirthdayServlet.html document from the previous example, changing the title and the action parameter of the FORM tag to point to a JSP rather than a servlet. Save the new document as BirthdayJSP.html in the same <j2ee_home>/default-web-app directory.

 <HTML> <HEAD><TITLE>Birthday JSP</TITLE></HEAD> <BODY>    <H1>When is your birthday?</H1>    <FORM method="GET" action="/Birthday.jsp">       Month <INPUT name="MONTH" size="2" type="TEXT"><BR>       Day   <INPUT name="DAY"   size="2" type="TEXT"><BR>       Year  <INPUT name="YEAR   size="4" type="TEXT"><BR>       <INPUT type="SUBMIT">    </FORM> </BODY> </HTML> 

Creating the JavaServer Page

Save the JSP as Birthday.jsp in the same <j2ee_home>/default-web-app directory as the HTML page. Unlike servlets, you do not manually compile the JSP or the servlet generated by the JSP translator.

 <%@page import=java.text.SimpleDateFormat,java.util.Calendar         contentType=text/html %> <%! Calendar cal         = Calendar.getInstance(); %> <%! SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); %> <HTML> <HEAD><TITLE>Birthday JSP</TITLE></HEAD> <BODY>    <% try {          cal.set(Integer.parseInt(request.getParameter("YEAR")),                  Integer.parseInt(request.getParameter("MONTH"))-1,                  Integer.parseInt(request.getParameter("DAY")));    %>          <H1>You were born on a <%= sdf.format(cal.getTime()) %> </H1>    <% } catch (NumberFormatException e) { %>          Invalid date    <% } %> </BODY> </HTML> 
Tip  

Do not place a semi- colon at the end of the Java scriptlet within the evaluation tags <%= ... %>.

Test the JSP

After creating the HTML document and saving the JSP source, you are ready to test creating a dynamic web page using the JSP. Load the HTML document using the following URL:

 http://localhost:8888/BirthdayJSP.html 

Enter in the values for your birthday, and click the Submit button to pass these parameters within the URL to the JSP. You should receive the same response HTML document as with the servlet example.

JavaBeans and Tag Libraries

Even with the separation of the static HTML tags from the JSP code, application logic still exists within the example JSP. JavaBeans, not to be confused with Enterprise JavaBeans, and tag libraries are two common methods to remove all of the business logic from the JSPs. Chapter 14 includes a thorough review of these topics, as well as other design improvements to JSPs.

Oracle Business Intelligence Beans

Oracle9 i Business Intelligence Beans (BI Beans) is a set of standards-based JavaBeans that provides analysis-aware application building blocks. BI Beans functionality is fully integrated into JDeveloper 10 g , allowing the developer to build Internet applications quickly and easily. These applications can expose the advanced analytic features of the Oracle database to both casual users and advanced users requiring ad-hoc query and analysis functionality. BI Beans fall into three categories:

  • Presentation Presentations need to be easy to build so any level user within an organization can produce a high-quality report. BI Beans provide three flexible data-aware presentation components : graph, crosstab, and table.

  • OLAP Online Analytical Processing (OLAP) beans make it easy to formulate complex questions and present answers in presentation beans. By using the graphical components provided with the BI Beans, a business user can specify complex queries in minutes, without knowing SQL. The OLAP beans also provide support to the APIs for advanced data manipulation including the capability to drill down on, change the layout of, or sort data.

  • Catalog services The BI Beans Catalog is used to save, retrieve, and manage all developer- and user-defined analytical objects, such as reports , graphs, favorite queries, and custom measures. Object definitions are stored in the Catalog as XML. The BI Beans Catalog is designed to support large, distributed user communities who share analytical objects in collaborative environments.

Enterprise JavaBeans

Enterprise JavaBeans (EJBs) are distributed, server-side components that allow the developer to focus on implementing the business logic. The EJB container takes care of all of the common architecture requirements such as security, connection and resource pooling, persistence, and ensuring transactional integrity.

EJBs exist within an EJB container such as the container included with Oracle Application Server 10 g . The EJB container is often a middle tier within an application, with a thin client at the presentation tier and a relational database such as Oracle at the database tier . There are fundamentally three types of EJBs:

  • Entity Entity beans model business concepts that are expressible as nouns, and often model persistent records, such as those within a relational database table. Entity beans have persistent state using either container-managed persistence (CMP), where the container automatically synchronizes the data between the bean and the database, or bean-managed persistence (BMP), where the bean manages its own state.

  • Session Session beans manage activities, and bring together various entity beans to process a transaction. Session beans do not have persistent state.

  • Message-driven Message-driven beans subscribe to asynchronous messages and coordinate the interaction between entity and session beans. Message-driven beans also do not have persistent state.

Implementing EJBs is a complex process, and is beyond the scope of an introduction chapter. Improper use of EJBs without an understanding of how to best query and update data in Oracle databases can lead to a poorly performing, nonscalable enterprise-wide application. Therefore, it is important to learn the basics of how Java can interact with Oracle first. After building on your knowledge of Oracle with your new Java skills, you will be ready to learn more about building and deploying EJBs.

Business Components for Java

Business Components for Java (BC4J) is JDeveloper s programming framework for building multitier database applications from reusable business components. BC4J provides a standards-based, server-side framework for creating production-quality J2EE applications. It includes design- time facilities and run-time services to simplify the tasks of building, debugging, customizing, and reusing business components. Applications developed with BC4J can be deployed on any J2EE platform and can be accessed from a wide variety of clients . The framework handles common development cases with built-in behavior, and developers can take advantage of these benefits without compromising their ability to control the way an application works. Any behavior provided by the framework can be easily overridden with a few lines of code, so developers are never locked into a certain way of solving problems.

There are two key objects in the BC4J framework:

  • Entity objects Entity objects store business logic and column information for a database table (or view, synonym, or snapshot).

  • View objects View objects use a SQL query to specify sets of business data that can be related to attributes from entity objects. View objects provide clients with row sets they can scroll through and update without concern for or knowledge of the underlying entity objects. Clients manipulate data by navigating through the result set, getting and setting attribute values; changes are made to the data in the underlying database when the transaction is committed.

BC4J also has the concept of an application module. The application module is the object with which the client and the database will interact. It contains the view objects that represent your view of the data and manages the transactions on that data.

The business components framework is a class library (in oracle.jbo.*) with built-in application functionality. Using the framework involves specializing base classes to introduce application-specific behavior, allowing the framework to coordinate many of the basic interactions between objects. By using the BC4J design-time wizards and editors that are built into Oracle JDeveloper 10 g , you can build business logic tiers by defining the characteristics of components. Wizards generate Java source code and XML metadata to implement the behavior you have specified. Because the generated code inherits from a framework, the Java source files are concise . You can use Oracle JDeveloper to edit the Java code to enhance or change the behavior, and test the application services, independent of the deployment platform.



Oracle Application Server 10g Web Development
Oracle Application Server 10g Web Development (Oracle Press)
ISBN: 0072255110
EAN: 2147483647
Year: 2004
Pages: 192

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net