Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

JSP - Architecture

The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.

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.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is furthur
passed on to the web server by the servlet engine inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of static HTML
content.
 Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated
servlet still matches the JSP's contents. This makes the process more efficient than with the other
scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.

Life Cycle of JSP

A JSP life cycle can be defined as the entire process from its creation till the destruction which
is similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
The following are the paths followed by a JSP

 Compilation

 Initialization

 Execution

 Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as
follows:

JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
The compilation process involves three steps:

 Parsing the JSP.

 Turning the JSP into a servlet.

 Compiling the servlet.

JSP Initialization:
 When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method:

public void jspInit()

{//Initialization code....}

 Typically initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.
JSP Execution:
 This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
 Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP
engine invokes the _jspService() method in the JSP.
 The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:

Void _jspService(HttpServletRequest req, HttpServletResponce res)

\\sevice handaling code

 The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup:
 The destruction phase of the JSP life cycle represents when a JSP is being removed from
use by a container.

 The jspDestroy() method is the JSP equivalent of the destroy method for servlets.


Override jspDestroy when you need to perform any cleanup, such as releasing database
connections or closing open files.

Phase of Java sever page

There are many types of phases:

 Translation Phase
 Compilation Phase
 Class Loading Phase
 Instantiation Phase
 Initialization Phase
 Servicing Phase
 Destroy Phase

Translation Phase:
 When client request comes for a jsp for the first time , jsp engine makes a full read of the
jsp verifies the syntactical corectness of the jsp elements and converts code into a servlet
source code.
 The process of JSP engine translating jsp into servlet nothing but translation phase of
JSP.
 Therefore , we say that jsp development is another style of development  asking container
to develop the servlet is nothing but JSP development.
 Container generated servlet class is also known as page implementation class.

Compilation Phase:

 The process of jsp engine compiling the page implementation class is nothing but
compilation phase of jsp.
 Jsp engine uses JASPER compiler to compile the container generated servlet class source
code
 In the life of the Jsp Translation and compilation happens only once unless jsp source
code modified.

Class Loading Phase:

 The java servlet class that was compiled from the JSP source is loaded into the container.

Instantiation Phase:

 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the response to requests and
other events. Typically, a JSP container is built using a servlet container. A JSP container
is an extension of servlet container as both the container support JSP and servlet.
 A JSPPage interface which is provided by container provides init() and destroy ()
methods.
 There is an interface HttpJSPPage which serves HTTP requests, and it also contains the
service method.

Initialization Phase:

public void jspInit()

//initializing the code

 _jspinit() method will initiate the servlet instance which was generated from JSP and will
be invoked by the container in this phase.
 Once the instance gets created, init method will be invoked immediately after that
 It is only called once during a JSP life cycle, the method for initialization is declared as
shown above

Servicing Phase:

 Servlet engine creates servlet request and servlet response object based on the web server
provided client information.

Servlet engine calls service method on the servlet instance by supplying two object
reference as arguments

 Once service method is completely executed, client request is served and request-
response cycle is complete.
 Within the service method request object is used to capture the user input.

Destroy Phase:

public void _jspdestroy()

//all clean up code

 _jspdestroy() method is also invoked by the container

 This method is called when container decides it no longer needs the servlet instance to
service requests.

 When the call to destroy method is made then, the servlet is ready for a garbage
collection

 This is the end of the life cycle.

 We can override jspdestroy() method when we perform any cleanup such as releasing
database connections or closing open files.
JSP Scipting Elements:

Srcripting Elements Exmple


Comment <%--comment--%>
Directive <%@directives%>
Declaration <%! declaration%>
Scriplet <%scriplet%>
Expression <%=expression%>

JSP Comment
JSP Comment is used when you are creating a JSP page and want to put in comments about what
you are doing. JSP comments are only seen in the JSP page. These comments are not included in
servlet source code during translation phase, nor they appear in the HTTP response. Syntax of
JSP comment is as follows :

<%-- JSP comment --%>

Example:
<%@ page %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<% -- This comment will not be visible to the colent in the page source --%>
</body>
</html>

JSP Directive Tag

Directive Tag gives special instruction to Web Container at the time of page translation. 

Typically, the page directive is found at the top of almost all of your JSP pages

Any number of page directives could be added within a JSP page, although the attribute/value
pair must be unique.

Simple page directive importing a java package:

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


JSP Declaration Tag

A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any
number of variables or methods within one declaration tag, as long as they are separated by
semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>

<%! int i = 0; %>

<%! int a, b, c; %>

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<%  java source code %>

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

1. Declare variables or methods to use later in the file (see also Declaration).
2. Write expressions valid in the page scripting language (see also Expression).

You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the
scriptlet produces output, the output is stored in the object, from which you can display it.

<%  

String name=request.getParameter("uname");  

out.print("welcome "+name);  

%> 

JSP expression tag

An expression tag 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, you can use an expression within text in a JSP file. Like
<%= someexpression %>

<%=20*10%>

<%= "welcome to jsp" %>  

Note:You cannot use a semicolon to end an expression

Explain the life-cycle methods in JSP?

The JspPage interface declares only two mehtods – jspInit() and jspDestroy() that must be
implemented by all JSP pages regardless of the client-server protocol. However the JSP
specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP
requests. This interface declares one method _jspService().

 The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called
before any other method, and is called only once for a servlet instance.we can override
this method using JSP declaration scripting elements.
 The _jspservice()- The container calls the _jspservice() for each request, passing it the
request and the response objects.we can not override this method.This method is defined
in HttpJspPage interface.
 The jspDestroy()- The container calls this when it decides take the instance out of
service. It is the last method called in the servlet instance. This method is called by
container when JSP is unloded from memory such as shutting down application or
container. This method called only once in JSP life cycle and we can override it.

Difference between JSP and Servlets


JSP Servlets
Servlets are Java programs that are already
JSP is a webpage scripting language that can
compiled which also creates dynamic web
generate dynamic content.
content.
JSP run slower compared to Servlet as it takes
Servlets run faster compared to JSP.
compilation time to convert into Java Servlets.
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.

In MVC, jsp act as a view. In MVC, servlet act as a controller.


JSP are generally preferred when there is not much servlets are best for use when there is more
processing of data required. processing and manipulation involved.
The advantage of JSP programming over servlets is
There is no such custom tag facility in
that we can build custom tags which can directly
servlets.
call Java beans.
We can achieve functionality of JSP at client side by
There are no such methods for servlets.
running JavaScript at client side.
*Fetch Data from Database using JSP
index.jsp

<HTML>
<HEAD>
<TITLE>Database Lookup</TITLE>
</HEAD>

<BODY>
<H1>Database Lookup</H1>
<FORM ACTION="basic.jsp" METHOD="POST">
Please enter the ID of the publisher you want to find:

<BR>
<INPUT TYPE="TEXT" NAME="id">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</BODY>
<HTML>
basic.jsp

<%@ page import="java.sql.*" %>


<% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); %>

<HTML>
<HEAD>
<TITLE>Fetching Data From a Database</TITLE>
</HEAD>

<BODY>
<H1>Fetching Data From a Database</H1>

<%
Connection connection = DriverManager.getConnection(
"jdbc:odbc:data", "YourName", "password");

Statement statement = connection.createStatement();

String id = request.getParameter("id");

ResultSet resultset =
statement.executeQuery("select * from Publishers where pub_id = '" + id + "'") ;
if(!resultset.next()) {
out.println("Sorry, could not find that publisher. ");
} else {
%>

<TABLE BORDER="1">
<TR>
<TH>ID</TH>
<TH>Name</TH>
<TH>City</TH>
<TH>State</TH>
<TH>Country</TH>
</TR>

<TR>
<TD> <%= resultset.getString(1) %> </TD>
<TD> <%= resultset.getString(2) %> </TD>
<TD> <%= resultset.getString(3) %> </TD>
<TD> <%= resultset.getString(4) %> </TD>
<TD> <%= resultset.getString(5) %> </TD>
</TR>
</TABLE>
<BR>
<%
}
%>
</BODY>
</HTML>

You might also like