Learning JavaServer Pages

Servlets provide an excellent mechanism for handling user requests for dynamic content, but they lack a useful way of displaying the response. Servlets rely on hard-coding of the presentation within the Java code. Any change in the look and feel of the presentation requires change to the code. This also mixes the roles of Web designers and Java programmers, which leads to chaos in the development process. JSP was developed to answer these concerns.

Servlets incorporate a tight coupling of content and logic, which reduces application flexibility. With JSP, you don't want to repeat the same issues. JSPs should be used with static content templates and generate dynamic content by calling presentation logic outside the JSP. Such presentation logic can be encapsulated in JSP tag libraries. This separation of the static content from the presentation logic makes the application more flexible to change. With JSP, Web designers can focus on developing only the system GUI with the required look and feel. On the other hand, Web developers can handle the presentation logic in taglibs, JavaBeans, or scriptlets. We'll talk more about these topics later today.

JSP is a cross-platform API, and it brings the power of server-side Java technology with static HTML pages. It provides an efficient method of delivering dynamic content through the Web. You can create and maintain JSP pages with conventional HTML/XML editors. A JSP page typically consists of the following elements:

  • Static HTML/XML components

  • Special JSP tags

  • Scriptlets

Writing a Simple JSP

The JSP API is defined on top of the Servlet API. Each JSP page inherently implements the HttpJspPage interface of the javax.servlet.jsp package. A JSP page is compiled into, and run as, a servlet (see Figure 7.6). Therefore, whatever experience you've gained about servlets thus far is applicable in developing JSPs. The main difference between servlets and JSPs is that servlet programming requires significant developer expertise, but JSP enjoys a much wider audience. JSP's primary owner is the page designer, who is responsible of proving contents to build the application's presentation. JSP is also used by the developer to provide the hooks and the references to the presentation logic. The main advantage of the concept of JSP is its inherent separation of presentation logic from content.

Figure 7.6. A JSP is compiled and run as a servlet.


Here is an example of a JSP, which is stored in the file simple.jsp:

<!doctype html public "-//w3c/dtd HTML 4.0//en">
<html>
  <%@ page errorPage="error.jsp" %>
							<%@ page isThreadSafe="true" %>
  <!-- Standard HTML Comment-->
<head>
   <title>Hello World from a JSP</title>
</head>
<body>
  <font face="Arial"> <h2>Hello World from an HTML </h2></font>
  <!-- An expression to print Hello World From a JSP to the out object -->
  <% out.print("<h2>Hello World from a JSP!</h2>"); %>
</body>
</html>
						

In this example, JSP tags are embedded into the HTML code (shown in bold). You are already familiar with the comment symbols <!-- comments --> used in HTML markup. The <%@ ... %> tag is used as a directive to the JSP container, and the <% exp %> tag is used to execute the expression exp, which is also called a scriptlet.

When a JSP is compiled and translated into a Java servlet, all the implicit methods of the HttpJspPage interface, such as _jspInt(), _jspDestroy(), and _jstService() are translated into the underlying servlet methods init(), destroy(), and service(). You don't have to override any JSP methods unless you have to implement such logic, which is what we're trying to avoid.

Both JSPs and servlets typically run within multithreaded containers (see Figure 7.7).

Figure 7.7. Multithreaded and single-threaded models of a servlet.


All running servlets and JSPs on the same container must handle concurrent requests, so you must be careful to synchronize access to any shared resources. Such shared resources include database connections and JMS destinations. By default, the service method of the JSP page is multithreaded. But if you need to change the default model and run using a SingleThreadModel, you can use the following directive:

<%@ page isThreadSafe="false" %>

This causes the JSP page implementation class to implement the SingleThreadModel interface, which results in the synchronization of the service method, and causes multiple instances of the servlet to be loaded in memory.

Tip

Try to avoid the single-threaded approach because it is not scalable, and it has a negative impact on response time.


The next section summarizes the basic syntax of JSP.

Learning JSP Basics

Learning JSP basic syntax is simple and can be classified into the following sections: comments, directives, scripting tags, and standard JSP actions.

Comments

There are two types of comments in JSP. You can use the HTML comments <!-- ... -->, as we did in the earlier example. This type of comment can be viewed in the page's source code. To avoid that, you can use the other type of JSP comments, the <%-- ... --%> tag:

<%-- JSP comment. Only stays at the server side. Can't be viewed by user --%>

As usual, comments are very powerful constructs for all programming languages.

Directives

JSP directives are messages to the Web container. They instruct the container what to do with the rest of the JSP page. All JSP directives are enclosed within the <%@ ... %> tag. The two main directives are page and include.

page Directive

The page directive is typically found at the top of almost all of your JSP pages. There can be any number of page directives within a JSP page. Two examples of page directives were included in the previous section, but here's another example:

<%@ page import="java.util.*, javax.naming.*" buffer="16k" %>

This imports the included packages for scripting and sets the page buffer to 16KB.

include Directive

The include directive performs a compile-time include. It enables you to separate your presentation into more manageable files, such as those for including a common page header, navbar, or footer. The included page can be any HTML, XML, or JSP page. An example of an include directive is as follows:

<%@ include file="header.html" %>

You can also use a fully qualified URL in the include directive.

Scripting Tags

All JSP tags start with <% and end with %>. Each scripting tag is recognized by an extra special character. The following sections discuss these scripting tags.

Declaring Variables and Methods

Like its Java parent, JSP is a strongly typed language. It requires all variables to be declared before they are used in your JSP code. This helps to create more robust code. When declaring a variable, you use the <%! ... %> tag. Remember to end your variable declarations with a semicolon. Here's an example of a declaration:

<%! float amount=0.0; %>

You can also declare methods using the same directive. For example, you can declare a method as follows:

<%! public float getCelsius(float f) {
  return (float) ((f - 32)/1.8);
}
%>

Executing Expressions

An expression is the assignment statement in JSP. You basically evaluate the expression and assign the result to the page's output stream. Typically, expressions are used to display simple values of variables or return values by invoking JavaBean or taglib methods. JSP expressions use the <%= ... %> tags.

<H3><%= myJavaBean.getTitle() %></H3>
<p> The value of temperature in Celsius: <%= getCelsius(temp) %> </p>
<%= myTagLib.getWarning(temp) %>

The value of each expression is evaluated and printed to the output stream.

Caution

JSP expressions do not end with a semicolon.


Executing Java Code with Scriptlets

Scriptlets are Java code fragments that can be embedded within the <% ... %> tags. The Java code can be used to generate dynamic content. Any valid Java code snippet can be used within a scriptlet. The following is an example of displaying the string Hello from my JSP page! within different heading types:

<% for (int m=1; m<=4; m++) { %>
<H<%=m%>>Hello from my JSP page!</H<%=m%>>
<% } %>

This example combines both scriptlets and JSP expressions. Scriptlets are useful mechanisms for dealing with synchronization issues, as described later today.

Summary of Scripting Tags

Each scripting element has a special type of tag syntax. All JSP tags start with <% and end with %>. An extra character is used to recognize the type of scripting element. The @ is used for directives, ! for declaration, and = for evaluating expressions. Table 7.2 summarizes the scripting tags used in authoring JSP pages and discussed in this section.

Table 7.2. Summary of Scripting Tags
TagPurpose
<!-- ... -->HTML or XML comments; can be viewed by the client
<%-- ... --%>JSP comments; stays on the server side
<% ... %>Scriptlets executing Java code fragments
<%@ ... %>page and include directives
<%! ... %>Declaration of variables and methods
<%= ... %>Evaluation and output expressions

JSP Implicit Objects

Implicit objects are convenient tools that are automatically provided by the Web container. They can be used within scriptlets and JSP expressions. You don't have to instantiate any of these objects. They are defined within the Servlet API. Table 7.3 lists a summary of the JSP implicit objects.

Table 7.3. Summary of Implicit Objects
ObjectPurposeScope
requestRepresents the HttpServletRequest.Request
responseRepresents HttpServletResponse. Not intended for use by page authors.Page
pageContextEncapsulates implementation-dependent features in PageContext.Page
applicationRepresents the ServletContext obtained from the ServletConfig object.Application
outJspWriter object that writes into the output stream.Page
configRepresents the ServletConfig for the JSP.Page
pageRepresents HttpJspPage. Synonym to the this operator. Not intended for use by page authors.Page
sessionRepresents HttpSession.Session
exceptionRepresents Exception object.Page

Standard JSP Actions (Taglibs)

Standard JSP actions are types of extension of tag libraries available by default and provided by the JSP API. In the next section, we'll introduce how to develop your own taglib. While the Web container is compiling a JSP into a servlet and encounters a taglib name, it generates all the classes required to perform such action. For example, the action

<jsp:forward page="register.jsp">

allows the response to be forwarded to another JSP.

Table 7.4 lists all the standard JSP actions provided by the JSP API. In the next section, you'll learn how to develop your own taglib.

Table 7.4. Summary of Standard JSP Actions (Taglibs)
Standard ActionAction Description
<jsp:useBean>Allows access to a JavaBean object, retrieved from a given scope or newly instantiated, through a named identifier.
<jsp:setProperty>Sets the value of a JavaBean property.
<jsp:getProperty>Outputs a JavaBean property, converted to a String.
<jsp:include>Allows inclusion of static and dynamic content within the current JSP page. Any HTML, JSP, servlet, image, or text can be included.
<jsp:forward>Forwards the responsibility for request handling to another static or dynamic resource.
<jsp:plugin>Instructs the browser to enable use of the Java plug-in with applets or JavaBeans.
<jsp:param>Used in connection with the include, forward, and plugin action tags to supply parameters in key/value pairs. Can be used as a subaction for <jsp:include>, <jsp:forward>, and <jsp:plugin>.

We'll cover the <jsp:useBean> action in more detail in the “Understanding JavaBeans” section later today.

Handling JSP Exceptions

The JSP architecture provides an elegant mechanism for handling runtime exceptions by making use of the page directive and the errorPage attribute. For example,

<%@ page isErrorPage="false" errorPage="errorPage.jsp" %>

instructs the Web container to forward any uncaught exception to the errorPage.jsp page. It is then necessary for errorPage.jsp to flag itself as an error-processing page by using the following directive:

<%@ page isErrorPage="true" %>

Note

Handling exceptions with this built-in routine is much more appropriate than providing your own exception handler, which would be required in all your JSP pages, and might not anticipate all cases that could be encountered at run-time.


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

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