28 JSP

Dr M. Vijayalakshmi

    1.1 Introduction to JSP

 

JSP stands for “Java Server Page” which is a high level abstraction of Java servlet technology. It is a server side technology which generates web pages dynamically in response to client requests. It provides a way to separate the generation of dynamic content (java) from its presentation (html) and hence in a regular html file, java code can be inserted for the dynamic parts using special tags. JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.

 

1.2Why use JSP?

 

JSP is easy to learn and it allows the developers to quickly produce web sites and applications in an open and standard way. It offers a robust platform for web development. The main reasons to use JSP includes Cross web server and Cross platform support,Java Language advantages (Object Oriented language) ,Component reusability by using JavaBeans and EJB.

 

1.3 Comparison of Servlets with JSP

 

Servlets

 

It is a Server side Java programswhich solves scalability issues because servlets run on the threads of execution and not on separate processes. It solves portability issues by running on every platform that supports Java and servlets are supported by all most popular web servers. The issues of servlets are: HTML tags are embedded in java programs within out.print () statements which reduces flexibility of programming. Moreover, application logic and formatting are closely tied and it is difficult to reuse code on a different logic.

 

JSP

 

It is also a server-side technology but it is the higher abstraction of servlets, which separates dynamic content from static contents of a web page where formatting and logic are not closely tied. Also,Java scriplets are embedded into html-like page to execute application logic and it separates the work ofjava programmers and page designers.

 

Advantages of JSP

 

The advantages of JSP are:

  • Easy to maintain and code.
  • High Performance and Scalability.
  • JSP is built on Java technology, so it is platform independent.

 

2.  JSP engines

 

To process JSP pages, JSP engine is required and it runs under the supervision of the servlet engine. It is typically connected with a web server or thiscan be integrated inside a web server or an application server. Some of the web servers that can be used for this are Apache Tomcat, Java Web Server, Web logic and Web Sphere.

 

2.1 JSP Architecture

 

Now, the architecture of JSP andits working functionalityis discussedhere.The overall view of the JSP Architecture is shown in Figure 1.The web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs.

   2.3 How JSP works ?

 

User gives JSP request page using web browser and the request is sent to the web server. From there, the JSP files are submitted to JSP Servlet Engine and based on the request, the output is sent back from web server to web browser and displayed as HTML pages. The working principle of JSP is given as the following pseudo code:

 

1.  User requests a JSP page using a web browser through Internet.

2. The JSP request is transmitted to the Web Server (request for a .jsp file) using a URL.

3. Web server processes the requested .jsp file and sends the corresponding JSP file to the JSP Servlet Engine.

4.  The Servlet engine checks whether servlet for the corresponding JSP file exists. If the servlet does not exists, it performs the following functions:

a. Translates JSP source code into servlet source code (Internally, all HTML code gets converted into suitable println statements).

b. Compiles the servlet source code to generate a class file (bytecode file).

c.  Loads the class file and a corresponding instance has been created for that.

d. Initializes the servlet instance by calling the jspInit() method.

e. Invokes the _jspService() method, transmits both the request and response objects.

    5. If the servlet already exists (instance is already running), simply forwards the request to the instance.

6. Now, the servlet output that has been generated is sent through the Internet from the web server to the web browser of the user and suitable HTML results are displayed on the user’s browser.

   

3 Life cycle of a JSP Page

 

A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to a Servlet has also been involved in the Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP Lifecycle steps,namely jspInit(),jspService() and jspDestroy(). The pictorial representation of a JSP page is shown in the Figure 2.

Figure 2:A JSP Lifecycle.

 

The detailed explanation of JSP Lifecycle is given below:

 

Translation: JSP gets translated into a Servlet for the first time. JSP container parses the JSP pages. It then translate the JSP pages to generate corresponding servlet source code. If JSP file name is hello.jsp, usually it is named as hello_jsp.java by the container.

 

Compilation: After translating into a servlet, it has been compiled and a class file gets created for that servlet. The compilation process involves three steps:

  • Parsing the JSP.
  • Turning the JSP into a servlet.
  • Compiling the servlet.

   Initialization: After successfully creating a class file, JSP engine invokesjspInit() to initialize the class file. Typically initialization is performed only once.

 

Service: After initialization, service (jspService()) method has been invoked and it handles the request and creates the response to be delivered to the browser. The _jspService() method of a JSP is invoked once per       request and it is responsible for generating the response for that request.This method is also responsible for generating responses to  the entire seven HTTP methods ie. GET, POST, DELETE etc.

 

Destroy: Once the service has been completed and response is sent back, jspDestroy() method has been invoked to clean up the resources.

 

If JSP page gets changed, JSP engine identifies automatically and translates it into a new servlet by passing through Translation, Compilation, Loading and Initialization phases.

 

3.2 A JSP Example

 

Let us see a simple JSP example as shown below:

 

<html>

<body>

<% out.print(2*5); %>

</body>

</html>

 

To create ajsp page, some html code has to be written, and saved with .jsp as extension. Here in this example, this is saved as index.jsp. Later, this index.jsp file need to be kept in a folder the folder could be pasted in the web-apps directory of apache tomcat (Web server) in order to run the index.jsp page.

 

3.3 How to run a simple JSP Page?

 

Inorder to execute a JSP page ,the following steps need to be followed :

  • Install the web server (For example: Apache Tomcat)
  • Start the web server & put the .jsp file in a folder (for example :myapplication as folder name)
  • Deploy the folder on the web server(example:Tomcat with port no: 8080)
  • visit the browser using the url specified below to view the web page http://localhost:port no/Folder name/Filename.jsp

Example : http://localhost:8080/myapplication/index.jsp

    4. Directory structure of JSP

 

Before continuing further with JSP, it is mandatory to know the directory structure of JSP.The directory structure of JSP page is same as the servlet. Here the .jsp page is either placed outside the WEB-INF folder or in any directory inside the Web-apps folder of Apache Tomcat as shown below in Figure 3.

 

 

 

4.1 Anatomy of a JSP page

 

Next let us have the brief knowledge about the anatomy of a JSP page. It contains two parts namely HTML/XML markups and JSP constructs/ Elements. These JSP constructs/Elements are of 3 different types consisting of:

 

1. Scripting elements, where Java code is inserted using scripting elements.

a. It is of 3 types: Scriplets, Declarations and Expressions.

2. Directives that controls overall structure and behavior of the generated servlet

3. Actions that control the behavior of the JSP engine to use existing components.

a. Additionally a JSP page includes JSP comments also.

 

5.  JSP Components and Tags

 

Some of most commonly used JSP components and tags are listed below:

 

 

5.1 JSP Directives

 

Each of the JSP elements are described in detail in this section. The JSP directives are messages that informs the web container that how a Java Server Page can be translated into a corresponding servlet.There are different three types of JSP directives:page directive, include directive and taglib directive

The general syntax for the JSP directives is

 

<%@ directive attribute=”value” %>

A glimpse of JSP Directives along with their description is shown in the Table 1.

 

 

5.1.1 Page directive

 

The pagedirective is used to provide instructions to the container regarding the current JSP page. Page Directives are allowed to code anywhere in our JSP page. By convention, page directives are coded at the top of the JSP page. Following is the basic syntax of page directive:

 

<%@ page attribute=”value” %>

 

We can also write the XML equivalent syntax as follows:

<jsp:directive.page attribute=”value” />

 

An example for page directive is shown below:

 

Example:

 

<%@ page import=”package.class” %>

<%@ page import=”java.util.*” %>

<%@ page contentType=”text/html” %>

<% response.setContentType(“text/html”); %>

 

5.1.2 JSP Include Directive

 The include directive is used to include the contents of any resource. It may be a jsp file, html file or text file. The job of the include directive is to include the original content of the included resource during page translation time (the JSP page is translated only once so it is better to include a static resource).The main advantage of include directive is Code Reusability.The syntax of include directive is as follows:

 

<%@ include file=”resourceName” %>

An example of include directive is

<html>

<body>

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

Today is: <%= java.util.Calendar.getInstance().getTime() %>

</body>

</html>

 

5.1.3 JSP Taglib directive

 

This provides output based on the common custom logic.It declares that our JSP page uses a set of custom tags, identified from the location of the library, and provides a means for identifying the custom tags in our JSP page.

 

<%@ tagliburi=“{TLD_FILE}” prefix=“{PREFIX}” %>

 

The components involved in tag libraries are listed below:

  • Tag handler class-Common custom logic and HTML generation
  • Descriptor configuration file – Directive’s  properties mapping information
  • Taglib directive- This is used in JSP to utilize the tag handler functionality

 

5.2 Scripting Elements

 

In JSP, it is possible to embed a java code inside a java server page using the scriplet tag.This provision has been enabled due to the existence of scripting elements. This can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.

 

There are three types of scripting elements:

  • Expression Scriplets
  • Declaration

    5.2.1 JSP expression tag

 

The code placed within the JSP expression tag has been evaluated, and converted to a string format and inserted in the place of expression as output stream of the response without using out.print() to write data.This is mainly used to print the values of variable or method. The expression element can contain any expression that is valid according to the Java Language specification but we cannot use a semicolon to end an expression.

 

The syntax of a JSP expression tag is listed below:

 

<%= Expression %>

 

An example of JSP expression tag is

 

<html>

<body>

<%= new java.util.Date() %>

<%=3+4 %>

</body>

</html>

 

The above expression tag is to output the current date instead of using a print statement.

 

5.2.2JSP Scriplets

 

A scriplet tag is used to execute/ insert arbitrary piece of java source code in a JSP and inserted in the _jspService() method. The syntax for JSP scriplet is

 

<%  java source code %>

 

An example of a JSP Scriplet that prints the user name is given below:

 

File: index.html

 

<html>

<body>

<form action=”welcome.jsp”>

<input type=”text” name=”uname”>

<input type=”submit” value=”go”><br/>

</form> </body>   </html>

File: welcome.jsp

<html>

<body>

<%String name=request.getParameter (“uname”);out.print(“welcome “+name);%>

</form>

</body>

</html>

    An Example to print the current date using Scriplet is given below:

 

<%java.util.Date d = new java.util.Date();out.println (“Date and time is :” + d);%>

 

5.2.3 JSP Declaration Tag

 

The JSP declaration tag is used to declare variables, methods and inner classes. It declares one or more variables or methods that can be used in Java code later in the JSP file. This can be used to declare the variables or methods before we use it in the JSP file.The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet.This doesn’t get memory at each request. The syntax of JSP declaration tag is

 

<%! variable or method declaration %>

 

The difference between a JSP Scriplet tag and Declaration tag is listed in Table 2.

 

An example of JSP declaration tag that declares the variables is shown below:

 

index.jsp

 

<html>

<body>

<%! int data=50; %>

<%= “Value of the variable is:”+data %>

</body>

</html>

    Another example of JSP declaration tag that declares the method is given below:

    index.jsp

 

<html>

<body>

<%!int cube(int n){return n*n*n;}%>

<%= “Cube of 3 is:”+cube(3) %>

</body>

</html>

 

5.3 JSPElements – Example

 

All the three JSP elements are reviewed in the above examples.A complete example depicting the usage of all the JSP elements along with its output is shown in Figure 4.

 

 

6 JSP Comments Tag

 

Comments are used to document the JSP pages and it can be inserted anywhere in the JSP page.Anything inside the comment tag is ignored by the JSP engine and not added to servlet’s source code.The syntax for JSP comments Tag is

<%– JSP comment    –%>

 

An example depicting the JSP comment tag is as follows:

 

<html>

<body>

<%– Prints cube results –%>

<% intcube(int n){return n*n*n;} %>

<%= “Cube of 3 is:”+cube(3) %></body></html>

 

7. Creation of a small Web application using JSP

 

In this section, we are going to see the creation of a small web application using JSP. Here two jsp files has been created – Index.jsp and Display.jsp. Index.jsp file accepts a name from the user through an user interface. Later, in Display.jsp file, the user name has been parsed and a welcome message has been displayed using that name.

 

Index.jsp

 

 <%@page contentType=”text/html” pageEncoding=”UTF-8″%> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

“http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head> 

<title>JSP Page</title> </head> 

<body>

<form method=”post” action=”display.jsp”> 

Enter Name &nbsp&nbsp&nbsp<input type=”text” name=”t1″ value=””><br> <input type=”submit” name=”result”> 

</form>

</body>

</html>

    Display.jsp

   <%@ page language=”java”%>

<html>

<body>

<%String str=request.getParameter(“t1”);out.println(“Welcome to” + ” “+ str);%>

</body>

</html>

Output of Index.jsp and Display.jsp has been given in the figures 5 and 6.

 

 

Summary:

 

In this module, we have discussed about the basics of JSP with its architecture and learnt the different ways in which a JSP works and discussed about the various elements of JSP with examples. We have also learnt the basic rules of the six JSP syntax elements—directives, declarations, scriplets, expressions, actions, and comments. Finally, we have seen a creation of a small web application using JSP.

 

Web Links