MODULE-IV

JAVA SERVER PAGES

Java Server Pages

Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately.

The Advantage of Servlets Over "Traditional" CGI

Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies.

·  Efficient

With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.

·  Convenient

Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

·  Powerful

Java servlets easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful thing like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.

·  Portable

Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or Web Star. Servlets are supported directly or via a plug-in on almost every major Web server.

·  Inexpensive

There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

The separation of user interface and program logic in a JSP page allows for a very convenient delegation of tasks between web content authors and developers. It also allows developers to create flexible code that can easily be updated and reused. Because JSP pages are automatically compiled as needed, web authors can make changes to presentation code without recompiling application logic. This makes JSP a more flexible method of generating dynamic web content than Java servlets, whose functionality Java Server Pages extend.

JSP and Servlets

Java servlets allow creating dynamically-generated web pages that include data from server-side Java objects. But the servlet approach to generating web pages is to embed HTML tags and presentation code within a Java class. This means that changes to presentation code requires modification and recompilation of the servlet source file. Because web authors who design HTML pages may not be the same folks as the developers who write servlet code, updating servlet-based web applications can be an involved process.

Enter Java Server Pages, which are an extension of the Servlet API. In fact, JSP pages are compiled into servlets before they are used, so they have all of the benefits of servlets, including access to Java APIs. Because JSP pages are generally presentation code with application logic embedded in them, they can be thought of as "inside-out" servlets.

While JSP pages mainly provide a higher-level method of creating servlets, they bring other benefits as well. Advantages of using JSP are:

§  JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.

§  JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.

§  JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.

§  Developers can offer customized JSP tag libraries that page author’s access using an XML-like syntax.

§  Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

In general, JSP allows developers to easily distribute application functionality to a wide range of page authors. These authors do not have to know the Java programming language or know anything about writing servlet code, so they can concentrate on writing their HTML code while you concentrate on creating your objects and application logic.

JSP Advantages

Separation of static from dynamic content:

With servlets, the logic for generation of the dynamic content is an intrinsic part of the servlet itself, and is closely tied to the static presentation templates responsible for the user interface. Thus, even minor changes made to the UI typically result in there compilation of the servlet. This tight coupling of presentation and content results in brittle, inflexible applications. However, with JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then created and used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine.

Write Once Run Anywhere:

JSP technology brings the "Write Once, Run Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily across platforms, and across web servers, without any changes.

Dynamic content can be served in a variety of formats:

There is nothing that mandates the static template data within a JSP page to be of a certain format. Consequently, JSP can service a diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML.

First JSP

JSP simply puts Java inside HTML pages. We can take any existing HTML page and change its extension to ".jsp" instead of ".html".What is happening behind the scenes is that the JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But every time we change the JSP file, it will be re-compiled again.)

Ex: <HTML>

<BODY>

Hello! Our First JSP

</BODY>

</HTML>

Adding dynamic content via expressions

As in the previous section, any HTML file can be turned into a JSP file by changing its extension to .jsp. Of course, what makes JSP useful is the ability to embed Java. Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in the JSP directory, and view it in a browser.

<HTML>

<BODY>

Hello! The time is now <%= new java.util.Date() %>

</BODY>

</HTML>

Notice that each time we reload the page in the browser; it comes up with the current time. The character sequences <%= and %> enclose Java expressions, which are evaluated at run time. This is what makes it possible to use JSP to generate dynamic HTML pages that change in response to user actions or vary from user to user.

JSP Processing

Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the container first turns the JSP page into a servlet (known as the JSP page implementation class).

The conversion is pretty straightforward; all template text is converted to println( ) statements similar to the ones in the hand coded servlet and all JSP elements are converted to Java code that implements the corresponding dynamic behavior. The container then compiles the servlet class.

Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page is a way to avoid hitting the first user with this delay. The JSP container is also responsible for invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is called the request processing phase. The two phases are illustrated in the figure given below.

JSP page translation and processing phases

JSP Elements

There are three types of JSP elements: scripting, directive and action

JSP Scripting Elements

JSP scripting elements enable us to insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

  1. Declarations of the form <%!code%> that are inserted into the body of the servlet class, outside of any existing methods.
  2. Expressions of the form <%=expression%> that are evaluated and inserted into the output.
  3. Scriptlets of the form <%code%> that are inserted into the servlet's service method.

Declaration

Declares a variable or method valid in the scripting language used in the JSP page.

JSP Syntax

<%! declaration; [ declaration;] + ... %>

Examples

<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

Description

A declaration declares one or more variables or methods that can use in Java code later in the JSP file. We must declare the variable or method before use it in the JSP file.

We can declare any number of variables or methods within one declaration element, as long as we end each declaration with a semicolon. The declaration must be valid in the Java programming language.

When we write a declaration in a JSP file, remember these rules:

·  We must end the declaration with a semicolon .We can already use variables or methods that are declared in packages imported by the <%@ page %> directive, without declaring them in a declaration element.

A declaration has translation unit scope, so it is valid in the JSP page and any of its static includes files. A static include file becomes part of the source of the JSP page and is any file included with an <%@ include %> directive or a static file included with a <jsp: include> element. The scope of a declaration does not include dynamic files included with <jsp: include>.

Expression

Contains an expression valid in the scripting language used in the JSP page.

JSP Syntax

<%= expression %>

Examples

Current time: <%= new java.util.Date () %>

Description

An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, we can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

When we write expressions in a JSP file, remember these points:

·  We cannot use a semicolon to end an expression (however, the same expression within a scriptlet requires the semicolon).

·  The expression element can contain any expression that is valid according to the Java Language Specification.

We can sometimes use expressions as attribute values in JSP elements. An expression can be complex and composed of more than one part or expression. The parts of an expression are evaluated in left-to-right order.

Scriptlets

JSP Syntax

<% code fragment %>

Examples

<%
String name = null;
if (request.getParameter("name") == null) {
%>
<%@ include file="error.html" %>

<%
} else {
foo.setName(request.getParameter("name"));
if (foo.getName().equalsIgnoreCase("integra"))
name = "acura";
if (name.equalsIgnoreCase( "acura" )) {
%>

Description

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.

Within a scriptlet, we can do any of the following:

·  Declare variables or methods to use later in the file.

·  Write expressions valid in the page scripting language.

·  Use any of the implicit objects or any object declared with a <jsp:useBean> element.

·  Write any other statement valid in the scripting language used in the JSP page.

Any text, HTML tags, or JSP elements must be outside the scriptlet.

Scriptlets are executed at request time, when the JSP container processes the client request. If the scriptlet produces output, the output is stored in the out object.

E.g.

<HTML>

<BODY>

<%

// This is a scriptlet. Notice that the "date"

// variable we declare here is available in the

// embedded expression later on.

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now <%= date %>

</BODY>

</HTML>

If we run the above example, we will notice the output from the "System.out.println" on the server log. This is a convenient way to do simple debugging. By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output.