1
JSP
Introduction
A web application consists of number of web pages. These web pages are generally developed using HTML. But pages developed using HTML produce static output or they have passive behavior. But at times you want to give different output to users by changing only a small part of the page. For example, if you want to display date and time or hit-count require a very small change in web page. To provide dynamic behavior to it, small programs can be included in HTML. This makes web pages to give different output for different users. Thus the behavior of the page becomes active.
Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing dynamic web-sites using JSP, web designers & developer can quickly incorporate dynamic elements into web pages using embedded Java & markup tags. The tags allow the user to present data & java object (Applet/JDBC/Java bean/servlet etc) allow storing business logic.
JSP specification is a standard extension defined on top of the servlet API. JSP‘s are text files with .jsp extension, which includes HTML/XML tags along with embedded java code.
Advantage Of JSP Technology
1.Portability
Since it is based on Java, JSP technology is platform independent. To run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be built for different type of web-servers to make them execute jsp files.
2.Reuse of Components & Tag Libraries
JSP technology emphasizes the use of reusable component such as Java Bean Components, Enterprise Java Bean Components etc. Data is the main reason of dynamic contents. The components may contain the code to obtain the data from databases or text files thus offering different contents to JSP files.
It supports different type of markup languages such as HTML/DHTML/XML. JSP also supports user-defined tags. For user-defined tags, the control is transferred to classes that contain the code, which should be executed. Any type of code such as JDBC, File Handling etc can be included in these classes. Thus a JSP page developer need not have considerable knowledge of Java.
3.Separation of static & Dynamic Content
Using HTML pages, we can send only static contents to web clients. If we use servlets, then the entire HTML code is required to be written in println statement, which is tedious. It also makes the entire page to be dynamic. JSP allows you to include dynamic content into the static contents separating the two from each other. The static contents are provided using HTML tags and dynamic contents are generated using scriptlets, user-defined tags etc. It also follows popular MVC (Model-View-Control) Design Pattern.
Fig.
4.Suitable for N-Tier Architecture
Because of features such as, platform-independence, support for different types of servers(web servers, database servers etc), markup languages, reuse of objects in the form of components etc. it is best suited for N-Tier architecture.
5.Performance
JSP pages are automatically compiled before execution. So it frees the job of programmer to explicitly compile the program. After compilation, the page is kept in memory for certain duration to serve for next requests. Thus the compilation activity is not done for every request(unless there are modifications in the page).
ASP VS JSP
Category / ASP / JSPPlatform Support / Windows only / All java enabled platforms
Type / Interpreted for every request / Compiled once executed again and again
Memory requirements / Loaded for each request / Loaded only once in memory
Web Server Support / IIS, PWS / Any web server – Apache, Netscape, IIS etc
Reusable objects / COM / DCOM / Java Beans, Servlets, EJB
Scripting Languages / VBScript, Java script / Java / Java script
Customizable tags / Cannot use custom tag libraries and is not extensible. / Extensible with custom tag libraries.
Memory leak protection / No / Yes
Servlets VS JSP
Servlets
/JSP
1. Servlets are less efficient in generating dynamic contents. / 1. JSP offers a clear separation of static and dynamic contents.2. Servlets files must be compiled by user. / 2. JSP files are automatically compiled.
3. Developers need to have significant knowledge of Java. / 3. Developers need not have significant knowledge of Java.
4. Management of beans is done using java code / 4. Management of beans is done using tags.
One.jsp
<html>
<body> Hello.
<% String uname=request.getParameter(“name”);
if(uname==null) uname=”world”;
%>
Hello, <%= uname %>!
</body>
</html>
<% ………….%> includes JSP/Java codes(Scriplet)
<%=…………%>includes variables
requestHttp request object
JSP Execution
When a server receives a request for JSP file, the request is sent to the JSP engine. The JSP engine checks whether it already exists in memory or not. If it doesn’t, then the engine compiles the JSP file into a special servlet file. The servlet is executed and the response object generated by it is sent to the client through the web server. Thus, when a JSP file is accessed for the first time, it requires some time to get the response. If the file is already present in the memory, then the engine checks whether the original JSP file is modified or not. If it is modified, then the JSP file is recompiled and executed. Otherwise it is just executed again. Thus JSP files are automatically recompiled, but pure servlet files should be explicitly recompiled.
Fig.
The JSP page class file extends HttpJspBase which in turn implements the Servlet interface. It contains 3 methods.
- jspInit : performs the initialization of a servlet. This method can be overridden.
- _jspService: executed for every request.
- jspDestroy: gets executed when servlet is removed by the server. This method can be overridden.
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 handcoded 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 following figure -
As long as the JSP page remains unchanged, any subsequent request goes straight to the request processing phase (i.e., the container simply executes the class file). When the JSP page is modified, it goes through the translation phase again before entering the request processing phase. The JSP container is often implemented as a servlet configured to handle all requests for JSP pages. In fact, these two containers -- a servlet container and a JSP container -- are often combined in one package under the name web container.
JSP Access Model / JSP Architecture
These are based on the location at which the bulk of the request process is preformed.
1.Model 1 (Page – Centric Design)
Fig.
In this type, the incoming request from a web browser is sent directly to the JSP page, which is responsible for processing it & replaying back to the client. There is still separation of using beans. Although, Model 1 architecture is suitable for simple application, it may not be desirable for complex implementation. This architecture usually leads to significant amount of script-lets embedded within a JSP Page. This may cause problems for web developers who don’t know much about Java, but required to develop large websites. The other disadvantage of this architecture is that each JSP page is individually responsible for managing application state & verifying authentication & security.
2.Model 2 (Servlet-Centic Design)
The Model-2 architecture is a server-side implementation of the popular MVC design pattern. Here the processing is divided between the presentation and front component. Presentation component are JSP pages that generate the HTML/XML response that determines the user interface when viewed by the browser. Front component controller do not handle any presentation issues, but process all the HTTP requests. Here, they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the users act which presentation components to forward the request to. Front components can be implemented as either a servlet or JSP page. The advantage of this architecture is that, there is no processing logic within the presentation component itself, it is simply responsible for retrieving any objects or beans that may have been previously created by the controller and extracting the dynamic content within for insertion within its static templates. This separation of roles and responsibilities of developers and page designers.
Another advantage of this approach is that the front component present a single point of entry into the application thus making the management of application state, security and presentation uniform and easier to maintain.
JSP Syntax Basics
1. Declarations
JSP Declarations let’s you define page level variables or methods. These are like variables or methods declared as class-level member. You can declare static or instance variables or methods. It is declared using <%!....%>.
For eg <%! int i=0;%> or <%! public void test(){…..}%>
numsq.html
<html>
<form method=get action=
Enter Num : <input type=text name=t1>
<input type=submit>
</form>
</html>
numsq.jsp
<html>
Sq:<%=getsq(request)%>
</html>
<%!
public int getsq( HttpServletRequest req)
{
int i=Integer.parseInt (req.getParameter(“t1”));
return i*i;
} %>
2. Expression
They are included <%=….%>. The results of evaluating the expression are converted to a string & directly included within the output page. These are used to display simple variables or return values of methods. For example <%= i %> or
<%= bean1.getname() %>
3.Scriplets
JSP code fragments or scriplets are included in<%.....%>. The code declared within these tags goes into service method. It includes java code which is to be executed by the server. For example:-
<%for (int i=1; i<=4;i++) { %>
<H <%=i%>Hello</H<%=i%>
<%}%>
o/p
<H1> Hello </H1>
<H2> Hello </H2>
<H3> Hello </H3>
<H4> Hello </H4>
4.Comments
<%-- ...... --.%> represents server-side comment.
5Directives
JSP directives are messengers for the JSP Engine. They don’t directly produce any visible O/P but tell the engine what to do with the JSP page. They are included in <%@.... %> tag. They are used to set the content type, import packages, control buffering, session management etc. The general syntax for directives are:-
<%@ directive attribute name = value…..%>
There are 3 types of directives :-
1.Page directives- It defines a no. of important attributes that affect the whole page directives is as follows :
(a)contentType – sets the MIME content-type
<%@ page contentType = “text/plain” %>
(b) import – specifies a list of classes & packages, the generated servlet
should import. By default, java.lang.*, javax.servlet.*; javax.servlet.http.* & javax.servlet.jsp.* are automatically imported.
<%@ page import = “java.io.*, java.util.*” %>
(c)buffer – specifies the minimum requirement size of the response in KBs.
A special value “none” indicates that content should be passed directly to the underlying PrintWriter object. Default is 8Kb.
<%@page buffer = “12Kb” %>
(d)autoFlush – specifies if the buffer should be flushed when it’s filled or IO
exception should be thrown. Default is true, because if this attributes is false, then a programmer should manually flush the buffer.
<%@ page autoFlush = “true” %>
(e)session – indicates the page want to have access to user’s session.
Default is true.
<%@ page session = “true” %>
(f)errorPage –specifies a page to display if an exception occurs within the
JSP page.
<%@ page errorPage = “/error.jsp” %>
(g)isErrorpage – indicates the page is intended to be used as the target on the
errorpage.
<%@ page isErrorPage=”true” %>
(h)language – specifies the scripting language used to write the code. Default
is java.
<%@ page language =”javascript”%>.
2. Include Directive
The include directive lets you separate your content into more manageable elements/files. For example, you can design separate html files that display common header/footer and include it in a jsp page. It includes the contents of given file in a current jsp page. For example, <%@ include file=”copyright.html” %>
3.Taglib Directive
This directive allows the page to use custom user-defined tags with the specified tag library name. The files have tld(tag library descriptor) extension. These files contain the specification of which classes should be executed when a user-defined tag is encountered. For example – <%@ taglib uri=”/WEB-INF/struts.tld” prefix=”struts” %>
Every user-defined tag is prefixes by a string specified by “prefix” attribute to avoid problems of tag-name clashes. For example, you can have your own tag called html with a prefix to differentiate it from HTML’s html tag.
For example <user:html> ….. </user:html>
pagedemo.jsp
<%@page contentType="text/html" import="java.util.Date" session="true" %>
Hello, User!!!
<br> Current time is <b> <%= new Date( ) %> </b>
<%@ include file="register.html" %>
<br> Session ID = <b> <%= session.getId( ) %> </b>
<br> Context Parameter : <b> <%= application.getInitParameter("country") %> </b>
JSP Implicit objects
JSP container makes available implicit objects to be used within scriptlets and expressions, without the programmer first having to first create them. These objects act as wrappers around underlying java classes and interfaces defined in servlet API. They are as follows –
1. request : represents HttpServletReqeust object used to access client’s info.
2. response : represents HttpServletResponse object used to send data to client.
3. out : represents JspWriter object that writes into the output stream.
4. config : represents ServletConfig object used to read initialization parameters.
5. session : represents HttpSession object used to identify a client and associate info with it.
6. page : represents HttpJspPage object. Alternatively, you can use this operator to refer to current page. This object is used in custom tag handler classes.
7. application : represents object of ServletContext which is used to obtain information about servlets that are running.
8. pageContext : represents object of PageContext which is used to access context data for page execution.
9. exception : represents Throwable object to handle uncaught errors and exceptions.
Synchronization Issue
By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared variable is synchronized .The other way to use is Thread Safe attribute of page directive <%@ page isThread Safe=”false” %>
The above declaration causes the JSP pages implementation class to implement single thread model interface, and having multiple instances of servlets to be loaded in the memory. The concurrent client requests are then submitted to individual servlet.
Servlet Instance 1Servlet Instance 2
Servlet Instance n
Servlet Pool
Req, Res ------
Req, Res ------
Req, Res ------
Servlet Container
The disadvantage of using the above method is when large number of concurrent requests are received, the total number of servlet-instances loaded at a time are limited. So a client may have to wait for some time to get a free servlet.
That’s why a better approach is to use isThreadSafe to be true (by default, it is true) and to explicitly control access to shared objects.
counter.jsp
<html>
<%! Integer count = new Integer(0); %>
<%
synchronized(this)
{
try
{
int I = count.intValue();
I++;
out.println(“this servlet has been accessed “ + I +“ number of times”);
count = new Integer(I);
}
catch(Exception e) {}
}
%>
</html>
Session Management
By default, all JSP pages participate in an HttpSession. Session is used for the purpose to identify a session and to associate information with it to be used for multiple requests coming from same browser window. Sessions are good place for storing beans and objects that need to be shared across other JSP pages and servlets, that may be accessed by the user. The session object is identified by a session id and stored into browser as a cookie. If cookies are not supported by the browser, then the session id may be maintained by URL rewriting a(modifying URL explicitly to include name-value pairs, for example . You cannot add primitive data types into the session. You can only store valid java objects identified by a unique key.
UserCounter.jsp
<html>
<%
int j = 0;
out.println( "<br> Session id : " + session.getId() + "<br>");
if( (Object) session.getAttribute("ucounter") == null)
{
j = 1;
session.setAttribute("ucounter", new Integer(1));
}
else
{
Integer k = (Integer) session.getAttribute("ucounter");