Java Server Pages


JSPs represent a Java-based technology that allows the development of dynamic web sites. A major strength of JSPs is that they allow programmers to produce dynamic content using an HTML-like syntax. A JSP container is similar to a servlet container, except that it provides support specifically for JSPs.

Java Server Pages not only offer developers automatic servlet generation, but also eliminate the need for manually writing doGet() and doPost() methods. Additionally, the JSP model separates presentation tasks from back-end tasks.

The JSP Life Cycle

JSPs begin life as a text file and are translated to servlets. The translation involves conversion of JSP source code into servlet source code by the JSP container. This process is commonly referred to as compilation of a JSP page into a servlet.

Note

Don’t confuse the process of converting JSP source code to servlet source code with compilation of Java code into bytecode.

After the conversion process is complete, the servlet is subsequently compiled. Because JSPs are converted to servlets, they inherit a servlet’s dependence on the request-response model. When the JSP container translates the body of a JSP page into a servlet, it creates a new class that implements the javax.servlet.Servlet interface. This new class contains a method called _jspService() and is constructed from the body of a JSP page. In addition, the container bases the newly generated class on a class whose service() method calls _jspService(). A JSP page is translated to a method that maps requests to responses based on the JSP’s page contents.

How are contents translated? The simplest part of the JSP source file is translating template text. This means translation of the page segment that does not contain page directives, a scripting element, an action, or anything else related directly to a JSP page. Template text can be HTML or XML. For example, a simple text could be converted into a call that looks like the following. Initially:

<p>Template plain Text</p>

is translated to this:

out.println(“<p>Template plain text</p>“);

Scripting expressions are easy to translate into servlets. This is because the Java code is translated as is with no modification.

Page Translation and Execution

Processing JSP pages consists of two phases, the translation phase followed by the runtime phase. First, the JSP page is converted to a servlet. The second phase occurs when the container receives a request. Then, the servlet runs.

Execution Implications

The translation occurs only when required. For example, if the JSP page is not altered in any way, there is no justification for generating a new servlet. On the other hand, if the page is modified, a new translation is required.

Note

JSP also supports precompilation of JSP pages into servlets. This method enhances performance by avoiding the time-consuming compilation of a page when first requested.

JSP Specialized Tags

Table 2-4 presents several JSP tags.

Table 2-4: JSP Tags

Syntax

Description

<%code fragment%>

A scriptlet tag contains a code fragment and one or more lines of code. No method needs to be declared because the code fragments become part of the servlet's service() method when the JSP is compiled.

<%!declaration %>

This is a method or variable declaration. The complete method must be contained within the tag. It is subsequently compiled into a method or variable declaration in the servlet.

<%- - comment - -%>

This represents a JSP comment that is never passed to the browser.

<%= expression %>

This represents an expression and contains any valid Java expression. The result is displayed where the expression lies on the page.

<%@ taglib uri=“path to tag library” prefix=“tag prefix” %>

This is a taglib directive. It makes a tag library available for use in the JSP by specifying the location of the tag library and the prefix to use with its associated tags. Directives like this should always be the first lines in a JSP page.

The JSP specification also includes standard tags for bean use. The usebean directive creates an instance of a specific JavaBean class. If an instance is present, it is retrieved; otherwise, it is created. The setProperty and getProperty tags allow you to manipulate properties of a given bean. In summary, most Java code becomes part of the servlet’s service() method when the JSP page is compiled to a servlet. However, this does not include code contained within declaration tags. The service() method is always called whenever a client performs a GET or POST operation.

The following examples demonstrate how to use the JSP tags described in Table 2-4.

The code fragment:

<html>
<head>
<title>
CodeFragment
</title>
</head>
<body bgcolor="#ffffff">
<h1>
<%= "Greetings, IFCE New Customer" %>
</h1>
</body>
</html>

The output occurs directly at the point where the expression is positioned on the page.

A JSP declaration:

<%! int i = 0; %>

A comment:

<%--This comment is never passed to the browser --%>

An expression:

<%= "2 * Math.PI * radius"%>

A taglib directive makes the tag library available for use in the JSP by specifying the location of the tag library and the prefix to use:

<myTagLibrary:customAction attribute="%= value %>" />

This particular example is interesting because the JSP scripting expression specifies the value of a JSP action’s attribute. Here is another example:

<jsp:setProperty name="login" property="visits"
value="<%= previousVisits + 1 %>"/>

The following example presents a simple JavaBean class to display a JSP that uses it:

package com.taglib.dpsjsp.firststeps;
public class HelloBean {
String name = "world";
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}

Although this is a primitive Java class, it contains a single instance variable, name, which refers to a string. The value of this string is “world.” External code can retrieve the name using the getName() method. The following Java Server Page can consume this JavaBean using the following page directives:

<html>
<body>
<p>
<jsp:useBean
/>
<jsp:setProperty name="hello" property="name"/>
Hello, <jsp:getProperty name="hello" property="name"/>!
</p>
</body>
</html>

The first action tag allows the JSP page to use the bean, identified by a particular class name and ID. In this scenario, we use an instance of the HelloBean Class and call “Hello”. The <%jsp:setProperty() %> tag causes the request parameter called name to be handed as a String parameter to the bean’s setName() method. Okay, this example is not complex nor original (everyone writes one of these), but it demonstrates how a JSP calls and uses a JavaBean.

JSP Page Directives

Directives convey processing information about the page to the JSP container. However, note that directives do not produce any output transparent to end users when a page is requested. Instead, they generate various side effects that alter the manner in which the JSP container processes a page.

Table 2-5 displays attributes supported by the page directive. By viewing this table, it is clear that JSP permits specifying multiple page directives on a single page.

Table 2-5: Attributes Supported by the page Directive

Attribute

Value

Default

Demos

info

Text string

None

info=“login form.”

language

Scripting language name

“java”

language=“java”

contentType

MIME type,
char set

contentType=“text/html”
charset=“ISO-8859-1”
contentType=“text/xml”

pageEncoding

Character set

“ISO-8859-1”

pageEncoding=“ISO-8859-1”

extends

Class name

None

extends=“com.taglib.dpjsp
.MyJspPage”

import

Class and/or
package names

None

import=“java.net.URL” import=“java.util.*, java.text.*”

session

Boolean flag

“true”

session=“true”

buffer

Buffer size,
or false

“Skb”

buffer =“20kb”
buffer=“false”

autoFlush

Boolean flag

“true”

autoFlush=“false”

isThreadSafe

Boolean flag

“true”

isThreadSafe=“true”

errorPage

Local URL

None

errorPage=“results/failed.jsp”

isErrorPage

Boolean flag

“false”

isErrorPage=“false”

Table 2-6 presents methods used to convert expression values into strings.

Table 2-6: Methods Used to Convert Expression Values into Strings

Value Type

Conversion to String

boolean

java.lang.Boolean.toString(boolean)

byte

java.lang.Byte.toString(byte)

char

java.lang.Character(char).toString()

double

java.lang.Double.toString (double)

int

java.lang.Integer.toString(int)

float

java.lang.Float.toString(float)

long

java.lang.Long.toString(long)

object

toString() method of object's class

Table 2-7 presents JSP implicit objects and their APIs for the HTTP application.

Table 2-7: JSP Implicit Objects and APIs for HTTP Applications

Object

Class or Interface

Description

page

java.servlet.jsp.HttpJspPage

Page's servlet instance

config

javax.servlet.ServletConfig

Servlet configuration data

request

javax.servlet.http
.HttpServletRequest

Request data

response

javax.servlet.http
.HttpServletResponse

Response data

out

javax.servlet.jsp.JspWriter

Output stream for page content

session

javax.servlet.http.HttpSession

Data shared by all application pages

application

javax.servlet.jsp.PageContext

Context data for page execution

pageContext

javax.servlet.jsp.PageContext

Context data for page execution

exception

java.lang.Throwable

Uncaught error or exception

Best Practice for JSP Page Processing

The best practice for designing a JSP page is separating the presentation code from the processing code. Place the presentation code in the JSP program and place all processing code in Enterprise JavaBeans. The JSP program code should call EJBs whenever the JSP program needs to process data. Perhaps the greatest benefit of doing this is that other enterprise applications can share processing code. This is also desirable because processing logic is not present in the JSP program, making the code much easier to read.

Note

I have chosen to present only basic information about JSP pages. For a complete examination of this vast technology, consult the numerous texts that deal exclusively with the entire range of JSP services.




.NET & J2EE Interoperability
Microsoft .NET and J2EE Interoperability Toolkit (Pro-Developer)
ISBN: 0735619220
EAN: 2147483647
Year: 2004
Pages: 101
Authors: Simon Guest

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