Showing posts with label jsp pages. Show all posts
Showing posts with label jsp pages. Show all posts

Sunday, 18 December 2011

Scripting in JSP Pages

JSP scripting elements allow you to use Java programming language statements in your JSP pages. Scripting elements are typically used to create and access objects, define methods, and manage the flow of control. Many tasks that require the use of scripts can be eliminated by using custom tag libraries, in particular the JSP Standard Tag Library. Because one of the goals of JSP technology is to separate static data from the code needed to dynamically generate content, very sparing use of JSP scripting is recommended. Nevertheless, there may be some circumstances that require its use.
There are three ways to create and use objects in scripting elements:
  • Instance and class variables of the JSP pages servlet class are created in declarations and accessed in scriptlets and expressions.
  • Local variables of the JSP page's servlet class are created and used in scriptlets and expressions.
  • Attributes of scope objects (see Using Scope Objects) are created and used in scriptlets and expressions.

Initializing and Finalizing a JSP Page

You can customize the initialization process to allow the JSP page to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the jspInitmethod of the JspPage interface. You release resources using the jspDestroy method.
The bookstore example page initdestroy.jsp defines the jspInit method to retrieve or create an enterprise bean database.BookDBEJB that accesses the bookstore database;initdestroy.jsp stores a reference to the bean in bookDBEJB.
private BookDBEJB bookDBEJB;
public void jspInit() {
   bookDBEJB =
      (BookDB)getServletContext().getAttribute("bookDBEJB");
   if (bookDBEJB == null) {
      try {

         InitialContext ic = new InitialContext();
         Object objRef = ic.lookup(
            "java:comp/env/ejb/BookDBEJB");
         BookDBEJBHome home =
            (BookDBEJBHome)PortableRemoteObject.narrow(objRef,
               database.BookDBEJBHome.class);
         bookDBEJB = home.create();
         getServletContext().setAttribute("bookDBEJB",
            bookDBEJB);

      } catch (RemoteException ex) {
         System.out.println(
            "Couldn't create database bean." + ex.getMessage());
      } catch (CreateException ex) {
         System.out.println(
            "Couldn't create database bean." + ex.getMessage());
      } catch (NamingException ex) {
         System.out.println("Unable to lookup home: " +
            "java:comp/env/ejb/BookDBEJB."+ ex.getMessage());
      }
   }
}
 
When the JSP page is removed from service, the jspDestroy method releases the BookDBEJB variable:
public void jspDestroy() {
   bookDBEJB = null;
}
 
Since the enterprise bean is shared between all the JSP pages, it should be initialized when the application is started, instead of in each JSP page. Java Servlet technology provides application life cycle events and listener classes for this purpose. As an exercise, you can move the code that manages the creation of the enterprise bean to a context listener class. See Handling Servlet Life-Cycle Events for the context listener that initializes the Java Servlet version of the bookstore application.

The Life Cycle of a JSP Page

A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.
When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.

Translation and Compilation

During the translation phase, each type of data in a JSP page is treated differently. Template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows:
  • Directives are used to control how the Web container translates and executes the JSP page.
  • Scripting elements are inserted into the JSP page's servlet class.
  • Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API.
For a JSP page named pageName, the source for a JSP page's servlet is kept in the file
J2EE_HOME/repository/host/web/
   context_root/_0002fpageName_jsp.java
 
For example, the source for the index page (named index.jsp) for the date localization example discussed at the beginning of the chapter would be named
J2EE_HOME/repository/host/web/date/_0002findex_jsp.java
 
Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete. The last incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred.
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle described in the section Servlet Life Cycle:
  1. If an instance of the JSP page's servlet does not exist, the container:
    1. Loads the JSP page's servlet class
    2. Instantiates an instance of the servlet class
    3. Initializes the servlet instance by calling the jspInit method
  2. Invokes the _jspService method, passing a request and response object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.

Execution

You can control various JSP page execution parameters using by page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page authoring tasks throughout the chapter.

Buffering

When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer with the following page directive:
<%@ page buffer="none|xxxkb" %>
 
A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another Web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.

Handling Errors

Any number of exceptions can arise when a JSP page is executed. To specify that the Web container should forward control to an error page if an exception occurs, include the following pagedirective at the beginning of your JSP page:
<%@ page errorPage="file_name" %>
 
The Duke's Bookstore application page initdestroy.jsp contains the directive
<%@ page errorPage="errorpage.jsp"%>
 
The beginning of errorpage.jsp indicates that it is serving as an error page with the following page directive:
<%@ page isErrorPage="true|false" %>
 
This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page.

Note: You can also define error pages for the WAR that contains a JSP page. If error pages are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.

The JSP Pages Examples

To illustrate JSP technology, this chapter rewrites each servlet in the Duke's Bookstore application introduced in The Example Servlets in as a JSP page. Table 11-1 lists the functions and their corresponding JSP pages.

Table 11-1 Duke's Bookstore Example JSP Pages 
FunctionJSP Pages
Enter the bookstorebookstore.jsp
Create the bookstore bannerbanner.jsp
Browse the books offered for salecatalog.jsp
Put a book in a shopping cartcatalog.jsp and bookdetails.jsp
Get detailed information on a specific bookbookdetails.jsp
Display the shopping cartshowcart.jsp
Remove one or more books from the shopping cartshowcart.jsp
Buy the books in the shopping cartcashier.jsp
Receive an acknowledgement for the purchasereceipt.jsp

The data for the bookstore application is still maintained in a database. However, two changes are made to the database helper object database.BookDB.
  • The database helper object is rewritten to conform to JavaBeans component design patterns as described in JavaBeans Component Design Conventions (page 270). This change is made so that JSP pages can access the helper object using JSP language elements specific to JavaBeans components.
  • Instead of accessing the bookstore database directly, the helper object goes through an enterprise bean. The advantage of using an enterprise bean is that the helper object is no longer responsible for connecting to the database; this job is taken over by the enterprise bean. Furthermore, because the EJB container maintains the pool of database connections, an enterprise bean can get a connection quicker than the helper object can. The relevant interfaces and classes for the enterprise bean are the database.BookDBEJBHome home interface,database.BookDBEJB remote interface, and the database.BookDBEJBImpl implementation class, which contains all the JDBC calls to the database.
The implementation of the database helper object follows. The bean has two instance variables: the current book and a reference to the database enterprise bean.
public class BookDB {
   private String bookId = "0";
   private BookDBEJB database = null;

   public BookDB () throws Exception {
   }
   public void setBookId(String bookId) {
      this.bookId = bookId;
   }
   public void setDatabase(BookDBEJB database) {
      this.database = database;
   }
   public BookDetails getBookDetails() 
      throws Exception {
      try {
         return (BookDetails)database.
            getBookDetails(bookId);
      } catch (BookNotFoundException ex) {
         throw ex;
      } 
   }
   ...
}
 
Finally, this version of the example contains an applet to generate a dynamic digital clock in the banner.
The source code for the application is located in the j2eetutorial/examples/src/web/bookstore2 directory created when you unzip the tutorial bundle. To build, deploy, and run the example:
  1. Go to j2eetutorial/examples and build the example by running ant bookstore2.
  2. Start the j2ee server.
  3. Start deploytool.
  4. Start the Cloudscape database by executing cloudscape -start.
  5. If you have not already created the bookstore database, run ant create-web-db.
  6. Create a J2EE application called Bookstore2App.
    1. Select FileNewApplication.
    2. In the file chooser, navigate to j2eetutorial/examples/src/web/bookstore2.
    3. In the File Name field, enter Bookstore2App.
    4. Click New Application.
    5. Click OK.
  7. Add the Bookstore2WAR WAR to the Bookstore2App application.
    1. Select FileAddWeb WAR.
    2. In the Add Web WAR dialog box, navigate to j2eetutorial/examples/build/web/bookstore2. Select bookstore2.war. Click Add Web WAR.
  8. Add the BookDBEJB enterprise bean to the application.
    1. Select FileNew Enterprise Bean.
    2. Select Bookstore2App from the Create New JAR File In Application combo box.
    3. Type BookDBJAR in the JAR Display Name field.
    4. Click Edit to add the content files.
    5. In the Edit Archive Contents dialog box, navigate to the j2eetutorial/examples/build/web/ejb directory and add the database and exception packages. Click Next.
    6. Choose Session and Stateless for the Bean Type.
    7. Select database.BookDBEJBImpl for Enterprise Bean Class.
    8. In the Remote Interfaces box, select database.BookDBEJBHome for Remote Home Interface and database.BookDBEJB for Remote Interface.
    9. Enter BookDBEJB for Enterprise Bean Name.
    10. Click Next and then click Finish.
  9. Add a resource reference for the Cloudscape database to the BookDBEJB bean.
    1. Select the BookDBEJB enterprise bean.
    2. Select the Resource Refs tab.
    3. Click Add.
    4. Select javax.sql.DataSource from the Type column.
    5. Enter jdbc/BookDB in the Coded Name field.
  10. Save BookDBJAR.
    1. Select BookDBJAR.
    2. Select FileSave As.
    3. Navigate to the directory examples/build/web/ejb.
    4. Enter bookDB.jar in the File Name field.
    5. Click Save EJB JAR As.
  11. Add a reference to the enterprise bean BookDBEJB.
    1. Select Bookstore2WAR.
    2. Select the EJB Refs tab.
    3. Click Add.
    4. Enter ejb/BookDBEJB in the Coded Name column.
    5. Select Session in the Type column.
    6. Select Remote in the Interfaces column.
    7. Enter database.BookDBEJBHome in the Home Interface column.
    8. Enter database.BookDBEJB in the Local/Remote Interface column.
  12. Specify the JNDI Names.
    1. Select Bookstore2App.
    2. In the Application table, locate the EJB component and enter BookDBEJB in the JNDI Name column.
    3. In the References table, locate the EJB Ref and enter BookDBEJB in the JNDI Name column.
    4. In the References table, locate the Resource component and enter jdbc/Cloudscape in the JNDI Name column.
  13. Enter the context root.
    1. Select the Web Context tab.
    2. Enter bookstore2.
  14. Deploy the application.
    1. Select ToolsDeploy.
    2. Click Finish.
  15. Open the bookstore URL http://<host>:8000/bookstore2/enter.

Saturday, 17 December 2011

JSP Examples Tutorial - Using Superclass Variables With Subclassed Objects


<HTML>
    <HEAD>
        <TITLE>Using Superclass Variables With Subclassed Objects</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Superclass Variables With Subclassed Objects</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            class BaseClass
            {
                public void start() throws java.io.IOException 
                {
                    localOut.println("Starting...<BR>");
                }
            }
            class DerivedClass1 extends BaseClass
            {
                public void fly() throws java.io.IOException 
                {
                    localOut.println("Flying...<BR>");
                }
            }
            class DerivedClass2 extends DerivedClass1
            {
                public void fly() throws java.io.IOException 
                {
                    localOut.println("Flying...<BR>");
                }
            }
        %>     
        <%
            localOut = out;     
            out.println();
            out.println("Creating a DerivedClass2 object...<BR>");
            BaseClass p = new DerivedClass2();
            p.start();
        %>
    </BODY>
</HTML>

JSP Examples Tutorial - Using Restricted Access


<HTML>
    <HEAD>
        <TITLE>Using Restricted Access</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Restricted Access</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            class BaseClass
            {
                protected void start()  throws java.io.IOException
                {
                    localOut.println("Starting...<BR>");
                }
            }
            class DerivedClass extends BaseClass
            {
                public void drive() throws java.io.IOException 
                {
                    localOut.println("Driving...<BR>");
                }
            }
        %>     
        <%
            localOut = out;     
            out.println("Creating an DerivedClass...<BR>");
            DerivedClass a = new DerivedClass();
            a.start();
            a.drive();
        %>
    </BODY>
</HTML>

JSP Examples Tutorial - Using Parameterized Constructors


<HTML>
    <HEAD>
        <TITLE>Using Parameterized Constructors</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Parameterized Constructors</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            class a
            {
                a() throws java.io.IOException 
                {
                    localOut.println("In a\"s constructor...<BR>");
                }
            }
            class b extends a  
            {
                b(String s) throws java.io.IOException 
                {
                    localOut.println("In b\"s String constructor...<BR>");
                    localOut.println(s);
                }
            }
        %>     
        <%
            localOut = out;     
            b obj = new b("Hello from JSP!<BR>");
        %>
    </BODY>
</HTML>

JSP Examples Tutorial - Using Inheritance in JSP


<HTML>
    <HEAD>
        <TITLE>Using Inheritance</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Inheritance</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            class BaseClass
            {
                public void start()  throws java.io.IOException
                {
                    localOut.println("Starting...<BR>");
                }
            }
            class DerivedClass extends BaseClass
            {
                public void drive() throws java.io.IOException 
                {
                    localOut.println("Deriving...<BR>");
                }
            }
        %>     
        <%
            localOut = out;     
            out.println("Creating an DerivedClass...<BR>");
            DerivedClass a = new DerivedClass();
            a.start();
            a.drive();
        %>
    </BODY>
</HTML>

JSP Examples Tutorial - Using Abstract Classes in JSP


<HTML>
    <HEAD>
        <TITLE>Using Abstract Classes</TITLE>
    </HEAD>
    <BODY>
        <H1>Using Abstract Classes</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            abstract class a
            {
                abstract String getText() throws java.io.IOException;
                public void printem() throws java.io.IOException 
                {
                    localOut.println(getText());
                }
            }
            class b extends a
            {
                String getText() throws java.io.IOException 
                {
                    return "Hello from JSP!";
                }
            }
        %>     
        <%
            localOut = out;     
            b bObject = new b();
            bObject.printem();
        %>
    </BODY>
</HTML>

JSP Examples Tutorial - Runtime Polymorphism


<HTML>
    <HEAD>
        <TITLE>Runtime Polymorphism</TITLE>
    </HEAD>
    <BODY>
        <H1>Runtime Polymorphism</H1>
        <%!
            javax.servlet.jsp.JspWriter localOut;
            class BaseClass
            {
                public void print() throws java.io.IOException 
                {
                    localOut.println("Hello from BaseClass...<BR>");
                }
            }
            class DerivedClass1 extends BaseClass
            {
                public void print() throws java.io.IOException 
                {
                    localOut.println("Hello from DerivedClass1...<BR>");
                }
            }
            class DerivedClass2 extends BaseClass
            {
                public void print() throws java.io.IOException 
                {
                    localOut.println("Hello from DerivedClass2...<BR>");
                }
            }
            class DerivedClass3 extends BaseClass
            {
                public void print() throws java.io.IOException 
                {
                    localOut.println("Hello from DerivedClass3...<BR>");
                }
            }
        %>     
        <%
            localOut = out;     
 
            BaseClass a1 = new BaseClass(); 
            DerivedClass1 b1 = new DerivedClass1(); 
            DerivedClass2 c1 = new DerivedClass2(); 
            DerivedClass3 d1 = new DerivedClass3(); 
 
            BaseClass baseClassVariable;
 
            baseClassVariable = a1;
            baseClassVariable.print();
 
            baseClassVariable = b1;
            baseClassVariable.print();
 
            baseClassVariable = c1;
            baseClassVariable.print();
 
            baseClassVariable = d1;
            baseClassVariable.print();
        %>
    </BODY>
</HTML>

JavaServer Pages Technology


JavaServer Pages (JSP) technology allows you to easily create Web content that has both static and dynamic components. JSP technology projects all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. The main features of JSP technology are
  • A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response
  • Constructs for accessing server-side objects
  • Mechanisms for defining extensions to the JSP language