JSP (Java server Pages)

A web application is a collection of HTML programs, DHTML, Java script, VBScript, XML, image, servlets and JSP. We know that every web application must resides in either web or application server. Based on the place where the web application programs are running (but the place where they are resides), the web application programs are divided into two types they are

  1. Static web resource programs
  2. Dynamic web resource programs
  1. Static web resource programs: Static web resource programs are those which are residing in the context of client(browser)

EX HTML, XML, Java Script etc.,

Static web resource programs are also known as client side static web resource technologies. The role of static web resource programs in web application to carry the client data and handover to server side programs.

2.Dynamic web resource programs: Dynamic web resource programs are those which are always resides in the server and also running in the context of server

EX: Servlet, JSP

Dynamic web resource programs are also known as server side dynamic web technologies. The role of dynamic web resource program is collect data from HTML program, process the data and gives response back.

Conclusion: In the web application static web resource programs always provide fixed/static response where as dynamic web resource programs always gives dynamic response.


Limitations of servlets: When we develop a web application by using servlets, we may get the following limitations.

  1. Servlets of web application requires strong knowledge of Java
  2. Servlets are very difficult for non Java programmers.
  3. We know that servlet is a mixture of both presentation (HTML) and business (Java) logic. At the time of development of servlet by using it may becomes imbalance because a servlet developer may be good in presentation logic or business logics but not in both.
  4. Servlets never provides separation between clarity between presentation and business logic. So that servlets are not providing parallel development.
  5. If we do any modification in a servlet then we need to perform redeployment process that is servlets modifications require redeployments which is time consuming process.
  6. If we develop web application with servlets then it is mandatory for the web application developer to develop web application configuration file(web.xml)
  7. Servlets does not provides any implicit objects(Implicit objects generally provided by containers during the dynamic program execution)
  8. Servlets does not contain a facility called custom tags development.
  9. Servlets are not providing global/implicit exception facility.
  10. Servlets are not containing page compilation concept.

When servlets are already available in the industry, what is the need of developing an another technology?

When servlets are released in the industry already there was a server side technology called ASP(Active server pages) which was developed by Microsoft. Industry experts appreciated powerful features of servlets but they felt servlets are hard in learning and hard in implementation. The technology called ASP appreciated by industry programmers because it is available in the form of tags. Learning tags based programming is easy and implementing the application is also easy but industry opinion about the ASP is ASP containing fewer facilities compared to servlets. Hence after taking the above industry opinion, SUN Micros system has come up with a technology called JSP with approach of tags based and inbuilt internal powerful features of servlets. Hence JSP tags based programming + internal features of servlets. So that each and every JSP program internally act as a servlet.

Writing a program in JSP is nothing but with respective tags.


Q) What is the difference between ASP and JSP?

A) ASP based applications runs only Microsoft provided Servers(IIS) but they never runs on non Microsoft servers like Tomcat, GlassFish, Weblogic etc., Hence technology ASP is treated as Server dependent but server side technology of JSP runs on each and every operating server irrespective their vendors hence JSP and whose applications are treated as servers\ side independent technologies and they full fill the slogan called WODA(Write once and deploy any where).


Advantages of JSP: If we develop any web application with a server side technology called JSP we get the following benefits.

  1. Learning JSP is does not requires strong knowledge of Java because writing a program in JSP is nothing but making use of tags.
  2. JSP programming is easy to learn and easy to implement for non Java programmers. JSP programming environment provides the separation between business and presentation logic.
  3. JSP programming environment provides Parallel development of web application. JSP programming contains implicit objects.
  4. JSP programming eliminates repeated redeployment problems that is as and when we modify the JSP, we need to save the JSP and makes a request and automatically it is taken care by container(JSP execution environment).
  5. JSP provides optional mechanism in configuring web application file(web.xml).
  6. JSP environment provides implicit/global exception handling mechanism.
  7. JSP programming provides an additional concept called custom tags development.
  8. JSP programming environment provides page compilation automatically.

JSP technology specification: JSP is one of the complementary technology for servlets with the aim of developing strong web applications.

  1. The meaning of technology is that technology specification released by original vendor and technology specification implementation done by third part software vendors like Database vendors, server vendors etc.,
  2. Since JSP is the server side technology, it is also having a specification released by SUN Micro system and it is implemented by third party server vendors like Tomcat(Apache Jakarta foundation), Web logic(Oracle corporation) Glassfish(oracle corporation) etc.,
  3. In the programming point of view specification is nothing but set of rules given in the form of abstract methods and present in interfaces so for the JSP specification SUN Micro system has developed lot of interfaces with the collection of abstract methods and these interfaces are developed by server vendors in the form of classes and released in the form of tags.
  4. Hence all the classes which are developed by various server vendors are common for al server softwares and they are available to the programmers in the form of jar files. For example on Tomcat server JSP related API is available in the form of jsp-api.jar and this jar file found in C:/Tomcat/common/jsp/lib folder.
  5. Similarly the JSP api is available in web logic in the form of weblogic.jar. The JSP technology released by SUN Microsystem in the month of September 1999 with JSP 1.0 version and later in the December 1999 JSP technology is enhanced to the industry on name JSP.

Phases in JSP: Whenever we develop a web application with JSP the JSP programmers will undergoes three types of phases they are

  1. Translation Phase
  2. Compilation Phase
  3. Execution Phase
  1. Translation Phase: The process of converting the .jsp program into .java program(equivalent to servlet) is known as Translation phase. In other words .jsp program is converted into .java program.

EX:  first.jsp converted into first-jsp.java. first-jsp.java is an equivalent servlet of first.jsp which is prepared by the container.

    Translation phase will be preformed by the container in the following occasions.

  1. Making a first request to .jsp program.
  2. Making a request to the modified JSP page.

Note: The process of converting one technology program (.jsp) into another technology(.java) is also known as automatic page compilation.

      2.Compilation Phase: The process of converting the .java program into .class file is known as compilation phase for example first-jsp.java is automatically compiled into first-jsp.class by the container. Compilation phase will be performed by the container in the following occasions.

  1. Making a first request to the JSP page
  2. Making another request to the modified JSP page.

 3.Execution Phase: Execution phase is nothing but processing the client request and gives response back to the client. During execution phase the container will perform following operations.

  1. Container loads equivalent servlet of JSP in its memory.
  2. Container instantiates an object of equivalent servlet of JSP.
  • Container will perform initialization process of equivalent servlet of JSP
  1. Container will perform request processing process/ service process and gives response back to client. The above i, ii, iii, iv steps of execution phase will be performed by the container in the case of first request to JSP or request to modified JSP from second to further subsequent requests, the container will perform step-iv of execution phase. The following diagram gives the diagrammatic representation of JSP.

Life cycle methods of servlets: We know that JSP is one of the server side technology and their applications are running in the context of server. Any kind of applications running in the context of server, it contains Life cycle methods(Loop back methods). JSP contains three life cycle methods they are 1. public void jspInit()

  1. public void _jspService(HttpServletRequest,HttpServiceResponse) throws ServletExceptiopn, IOException
  2. public void jspDestroy()
  1. public void jspInit(): It is one of the predefined null body method. This method will be called by the container only once when we make a first Request to the JSP program since this method is calling only once by the container, it is highly recommended for the web applicaton developer to write one time operations like opening files in read mode or write mode obtaining the Database connection, initialization of parameters etc., In general jspInit() contains block of statements which will always gives resource gathering logic
  2. public void _jspService():
    1. After executing jspInit() at the time of making first request, container will automatically calls _jspService(-,-) from second request to further sub sequent request container will call only _jspService(-,-)
    2. Hence this method will be called by the container each and every time whenever we make a request to the jsp program. Since this method is calling each and every time it is supposed to contain repeated operations like reading the records from the file, reading the records from the Database etc.,
    • in general this method always contains block of statements which will perform Request Processing logic _jspService(-,-) is not posble to override by programmer and this method is always override by JSP container.

    Note: As a JSP programmer what ever the request processing logic will use writing in the form of tags that logic will be automatically placed by the container with in the body of _jspService(-,-)

  3. Public void jspDestory():
    1. It is one of the predefined method defined with null body.
    2. This method will be called by the container automatically when the web application developer removes the war file name or web application from the context of server. Since this method is called when the web application was removed from the context of server, It is highly recommended to close the resources like files, Database connections etc., Hence JPS Destroy() always contains the block of statements which will perform Resource relinquishing logic.

    Note: All the above life cycle methods of JSP are internally calling by the container through the Life cycle methods of Servlet. That is init(-) is automatically calling jspInit(), service(-,-) is automatically calling _jspService(-), Destroy() automatically calling by _jspDestroy(). So in the JSP life cycle methods it is always recommended to override jspInit() and jspDestroy() but not recommended to override _jspService(-,-).

    Sun Micro system has prescribed the following standard format for development of JSP programs.

    If we write any program in JSP then it must be saved on same file name with an extension .jsp writing a program in JSP is nothing but making use of HTML tags for presentation logic and JSP tags for request processing logic. Along with HTML tags And JSP tags we may also use normal text and template text. Template text is a collection of normal with HTML tags. If a client makes a request to the JSP the client receives static response from HTML tags and whose related source code can be viewed in the browser(right click on browser and select view source) where as client receives dynamic response from JSP tags and whose source code can’t be viewed in browser.


Q) What are the difference between HTML tags and JSP tags?

HTML Tags JSP Tags
1.      HTML tags are developed by w3c organization.

 

2.      HTML tags are always used for the development of static web resource programs.

3.      HTML tags always generated static response.

4.      When static response is generated, the client side programmer can view HTML tags in browser window.

5.      HTML tags are not case sensitive.

6.      In most of HTML tags, following the order of attributes is optional.

 

7.      With HTML tags no more custom tags can be developed.

1.      JSP tags are developed by SUN Micro system and practically implemented by Server vendors.

2.      JSP tags are always used for the development of dynamic web resource programs.

3.      JSP tags always generate dynamic response.

4.      When dynamic response is generated a client side programmer can’t view JSP tags in the browser window.

5.      JSP tags are case sensitive.

6.      All the JSP tags related attributes and their order is mandatory to follow. Otherwise get translation problem.

7.      With JSP tags one can develop custom tags.

 

Note: A HTML program can contain a JSP program. That is a JSP program can be embedded within HTML tags and it is opposite in the case of servlets.


Implicit objects in JSP:

  1. In JSP programming we can have two types of Objects they are explicit objects and Implicit Objects.
  2. Explicit Objects are those which are created by Java programmer with respect to some classes/interfaces either directly or indirectly during the request processing logic.

EX: String s=new String(“java”)

Runnable r=new th1()

Here r and s are called explicit objects.

Implicit Objects: Implicit objects are those which are created by server during JSP program is under execution the following table gives nine implicit objects whose corresponding class name/interface name.

Implicit Object name Instantiated by
Request

response

out

config

application

session

exception

page

pagecontext

javax.servlet.http.HttpServletRequest

javax.servlet.http.HttpServletResponse

javax.servlet.jsp.JspWriter

javax.servlet.ServletConfig

javax.servlet.ServletContext

javax.servlet.http.HttpSession

javax.lang.Throwable

like java.lang.Object

javax.servlet.jsp.PageContext

 

All the above implicit variables are available to every JPS program except Exception. The object Exception will be visible if any Exception occurs in the JSP program.


JSP Tags: JSP tags are classified into four types for developing web applications they are

  1. Scripting elements
  2. JSP commenting tags
  3. JSP directives
  4. JSP standard actions

Scripting Elements: The basic aim of scripting elements is to develop preliminary programming in JSP. Preliminary programming programming of JP requires how to declare variables, how to define methods, how to form expressions and where to write business logic code.

Scripting elements are classified into three types

  1. Declaration tags
  2. Expression tafs
  3. Scriplets

Declaration tag: Declaration tag is used for three purposes they are

  • Defining the variables
  • Defining the user defined methods.
  • Overriding the JSP life cycle methods except _jspService(-,-)
Syntax1 (Standard Syntax)
<%! Variable declaration definition of user defined method overriding JSP life cycle methods%>
JPS XML based: 
<JSP: declaration>
Variable declaration definition of user defined methods overriding JSP life cycle methods %>

In single JSP program one can write either one or more number of declaration tags. Whatever the details we are written declaration tag of JSP program they are becoming member properties in the equivalent servlet of the JSP.

Declare the variables a, b, c and places 10,20,30 respectively

<%! 
int a=10, b=20, c=30 %>
(or)
<! int a=10
int b=20
int c=30%>
Al the above three variables of declaration tags will become data members in the equivalent servlets in JSP.
Override jspInit() for obtaining the database connection:
<%! Public void jspInit()
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl,”scott”,”tiger”);

Expression Tag: Expression tag is always used fro writing request processing logic which we are giving as a response back to client.

Syn1: (Standard syntax)
<% =Java expressions)
Syn2: (XML based)
<JSP:expression>

Whatever the Java expressions we are writing in the expression tag which will become as a part of out.println and it will be placed with in _jspService(-,-).

The Java expression tag should not be terminated by semicolon. If it will terminate by semicolon we will get compile time error.

EX: <%!
              Int a=10;
          Int b=20; %>
     sum=<%=a+b%>   (out.println(a+b))
     sum=<%=a+b;%>   Invalid(Compile time error)
EX2: 
<%! 
    int a=10;
    int b=20;  %>
<%!
  int sum()
{
return(a+b);
}
%>

Write a scriptlet which will calculate factorial of a given number by passing value of n through Query String

<%
int num=Integer.parseInt(request.getParameter("num"));
%>
    <%!
    int factorial(int n)
    {
        if (n == 1) {
            return n;
        }
        else {
            return n * factorial(n - 1);
        }
    }
    %>
       <%
      out.println(" <h1> The factorial of  " +num+"  is : " + factorial(num)+"</h1>");
    %>

JSP Directive tags: The purpose of directive tags is to supply or provides external or additional information to the current JSP program. JSP directive tags related information utilized by the JSP container during the JSP program execution, supplying the additional information or external information to the JSP pages represents importing the packages o fJSP including the static web resource programs content and getting web.xml information at the time of development of custom tag. JSP directive tags are classified into three types they are

  • iii) Taglib directives
  • ii) Include directives
  • i) Page directives

 

i) Page directives: The purpose of Page directrive is to provide external or additional information like importing the packages, specifying the content type, utilizing the current JSP page only.

Syn: <%@page attribute name1=val1,attribute name2=val2
-------------     
-------------   
Attribute namen=valn%>
     Page is one of the directive tag Attribute1, Attribute2,----------,Attributen represents name of the page directive attributes.
  1. Val1, val2, —–,valn represents the values for attributes of page directive by the convention of page directive it is highly recommended to write as a first statements in the current JSP program. That is one JSP program may contain many page directives an dall of htem must be written as first statements in the cureent JSP program.
  2. All the attribute names must be unique except import attribute that means all the attribute names to be specified only one but import attribute can be specified multiple times for importing multiple packages.

Page directive attributes divided into 11 types those are

  1. import
  2. ContentType
  3. extends
  4. errorPage
  5. isErrorPage
  6. autoFlush
  7. buffer
  8. sesson
  9. isThreadSafe
  10. isELIgnore
  11. language

1. import: This attribute is used to for importing either predefined packages of JSE or third party packages(Oracle corporation or IBM etc) or user defined packages to the current JSP program.

Syn: <%@page import=”packname1=val1 packname2=val2----packnamen=valn%>
                                  (or)
<%@page input=”packname1=val1”
 Import =”packname2”=”val2”
--------------      
--------------     
Import=packnamen=valn”%>
     In the above syntax the tag values can be separated by coma or separated by space. 

Example :

Date.jsp
<%@page import=”java.util.Date”%>
Current date and time=<%=new Date()%>
     In this Date.jsp program java.util.* package is treated as external information.

2]ContentType: The purpose of this attribute is to specify the MIME Type. MIME Type always makes us to understand the type of response like word document, except document, audio, pdf formats etc., The default value of MIME type in JSP or content type in JSP is text/html programmatically the type of MIME.

Syn: <%@pageContentType=”MIME Type”>

Example :

EX: <%@page contentType=”application/msword”

3] extends: We know that extends is inheriting the features of base class to derived class and base interfaces to derived interfaces. In the case of JSP programming the keyword extends is not available at programmer level because if the JSP programmer specifies ame class name to extends attribute then the equivalent servlet of the JSP related class is suppose to extends our class which is illegal the equivalent servlet of this JSP related class is already extending http servlet. Hence the extends attribute at server developer levels only.

<%@page extends=fully Qualified name of the class%>

4.errorPage

5. isErrorPage    :

The basic aim of the above tags is to achieve implicit or automatic Exception Handling fecility.

Syn:

<%@Page isErrorPage=”true||false”   errorPage=”path of error page%”>

The default value of isErrorPage is true that is in the same JSP page we need to write try and catch blocks for dealing with exceptions and it leads to a lengthy process for utilizing try and catch blocks in the all JSP programs to avoid that it highly recommended to write a separate JSP program for dealing with all the Exceptions of the JSP programs. To do this pass the value false for isErrorPage immediately specifies the name of the JSP program where exceptions are handled. errorPage attribute always takes name of the program where exceptions are handled. Hence if isError=false then use error page if isErrorPage value is true we should not use error page.

err.jsp
Name of the exception=<%=exception%>
         (or)
Name of msg=<%exception.getMessage()%>

Example : Write a JSP program which illustrate the concept of errorPage and isErrorPage

Write a JSP program which illustrate the concept of errorPage and isErrorPage
x.jsp
<%@page isErrorPage="false" errorPage="ErrorPage.jsp"%>
<h1>Result =<%=30/0%></h1>

This program makes us to understand if any exception occurs in this program, that exception will not be handled by current JSP program but it will be transferring that exception to some other JSP program where exception is handled.

ErrorPage.jsp
<%@page isErrorPage="true"%>
<h1>							      
Exception is<%=exception%></h1>						        
<br>
<h1>Generated .......
    Exception Message is <%=exception.getMessage()%></h1>				        

 

6.autoFlush

7.buffer:

 autoFlush is one of the page directrive attribute which will take either true or false if autoFlush is true then the container understands that there response object will receive the data with 8 kb buffer or out.close is taken place that is the data of the response object will be flushed or rendered or gives to the client either 8KB buffer is full or out.close is taken place. In JSP programming environment default buffer size is 8KB and it can be increased or specified with the multiples of 2.

<%@page autoFlush=”true” buffer=”name”> //invalid
<%@page autoFlush=”true”%> //valid
     IF autoFlush is false then container understand the response data will be rendered or flushed to the client until specified buffer size is filled or out.close is taken place when we use autoFlush=”false” then it is mandatory to specify buffer size.
EX: <%page autoFlush=”false” buffer=16kb>
<%page autoFlush=”false”> //invalid
Syntax: 
<%@page autoFlush=”true||false” buffer=”name”||8kb||6kb%”>

8. sesson: We know that http protocol is one of the stateless protocol it maintains identity of client for a limited period of time. The real world servers like Tomcat, weblogic etc., will follow the http protocol so that these servers are known as stateless servers. Stateless servers remembers previous requests and response details this process leads the identification problems regarding multiple requests of the same user in order to avoid this problem all the server side technologies provides session tracking API(Cookies, Http Sessions, Hidden Form Fields, url rewriting). In JSP environment JSP containers are by default having Http Sessions as a default session tracking mechanism. To use it we use session attribute of page directive session attribute takes two valus they are true or false.

<%@page session=”true||false”%>

Case(i): If session=true and client makes first request.

  1. A) IF Container will create session first time

Case(ii): If session=”true” and client makes second and further subsequent requests then

  1. A) session will be continued by checking whether it is created or not.

Case(iii): If session=”false” and client makes first request then

  1. A) JSP container never creates a session.

Caseiv): If session=”fase” and client makes second and further subsequent requests then

  1. A) session will be continued without checking whether it is created or not.

Conclusion: By observing all the above cases it is highly recommended to the JSP programmer to write the session attribute value always true for continueing the session always. So that session data can be carried from first request to second and further subsequent requests by making use of session implicit variable.

9. isThreadSafe

Syn: <%@isThreadSafe=”true||false”>

isThreaedSafe is one of the page directrive tag and it takes either true or false the default value of the isThreadSafe=”true”. If isThreadSafe=”true” then we get

  1.  Inbuilt synchronization concept
  2.  Container provides concurrent access

If isThreadSafe=”false” then

  •  container won’t provide inbult synchronization mechanism
  •  container provides only sequential access.

10. Language: The purpose of language attribute is to make the container to understand about type of language used by the programmer for writing scriptlets, expressions and declarations the default value of language attribute is Java when we are writing client side validations by using Java script then the value of the language attribute is Javascript. In the near future or in the upcoming versions of the JSP the language attribute may contain other languages like COBOL, .NET etc.,

EX: x.jsp
<%page language=”java”%>
-------      
--------     
Java loading standards (default)
y.jsp: 
<%page language=javascript”%>
-----------    
----------    
-----------   
%>
Note: Java and Javascript is no way related but  javascript can be used for client side validations. The vendor of Javascript is Netscape, vendor of Java is  SUN Microsystem.    

11. isELIgnore:

We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e. Expression Language is enabled by default. We see Expression Language later.

<%@ page isELIgnored=“true” %>//Now EL will be ignored


Include Directives: This directive always include static web resource programs during the transaction phase. In other words whatever the static web resource name we specify which will directly placed in the equivalent servlet of the JSP

Syn: <%@include file=”name of the static web resource program%>

Here include is one of the directive tag and it supplies external information regarding static web resource program to the current JSP.

Here file is an attribute of include directive which will take the name of the static web resource program.

Conclusion: include directive tag deals with only static web resource programs but never deals with dynamic web resource programs at any point of time one can use multiple includes in the current JSP page.

x.jsp: 
<%@include file=”header.jsp”>
<% Date d=new Date();
Out.println(d);
%>
<@include file=”footer.html”>

Scope: This attribute represents the availability of Java Bean class object name. Scop attribute takes four values or Java Bean class object will have four types of scopes they are

  1. a) page: If scope=page then the data of Java Bean is available to the current JSP page only. Once the response of current JSP page is completed, an object of Java Bean class will be destroyed by the container.
  2. b) request: If scope=request then the data of Java Bean class object is available to those JSPs which are participating in JSP chaining once the JSP chaining gives the response back to the client then container will automatically destroy the Java Bean class object. The number of JSP programs participated in processing single request of the user is known as JSP chaining.
  3. c) session: If scope=session then the data of Java Bean class object can be available all those JSP programs which are participating JSP session tracking. One the session is completed, automatically container will destroy an object of Java Bean class

In request scope their exists single request and response objects where as in session scope their exists multiple requests and responses


What are the differences between <%@include ——-%> and <jsp include ——/>

<%include%> <JSP:include—–/>
1.      It is one of the directive tag.

2.      Directive include always participates in the compile time/translation time.

3.      Directive include is always used for including static web resource programs only but not dynamic web resource programs.

4.      Directive include includes the static web resource program’s source code in the equivalent servlet of JSP during translation phase.

5.      Directive tag include takes file as an attribute.

1.      This is one of the standard action tag.

2.      Action include participates at runtime (execution   phase).

3.      Action include can be used always for including both static and dynamic web resource programs.

4.      Action include includes the result of static web resource programs in the result of equivalent servlet of the JSP during execution phase.

5.      Action include takes page an attribute which illustrate the JSP and servlet.