Sunday, 19 August 2012

JavaServer Pages

Like Servlets, JSP is also a specification which enables Web developers and designers to rapidly develop and easily maintain, information-rich, dynamic Web pages.

Need for JSP
With servlets, it is easy to read form data, read HTTP request headers, use cookies and session tracking, share data among servlets....

But, it really difficult to use those println() statements to generate HTML and to maintain that HTML.

JSP Framework on the other hand use regular HTML for most of the pages and mark servlet code with special tags.
This JSP technology combine with Java code and HTML tags in the same document to produce a JSP file.

Below figure shows how JSP works:

The web browser makes a request to JSP source code. This code is bifurcated into HTML and java code by the JSP parser.
The java source code is compiled by the Java compiler resulting in producing a servlet equivalent code of a JSP.
The servlet code is intermixed with HTML and displayed to the user.
Here a JSP only passes through all these phases when it is invoked for the first time or when the changes have been made to JSP. Any later call to JSP does not undergo of compilation phase.

JSP Ingredients


Comments are ignored by JSP-to-servlet translator. Two types of comments are possibly used in JSP.
1) HTML comment: These comments are shown in browser, means on taking view source of the web page; these sorts of comments can be read. Format of HTML comments is like to:
              <!-- comment text-->

2) JSP comment: These comments are not displayed in browser and have format like:
<%-- comment text --%>


The format of writing a Java expression is: <%= Java expression %>.
These expressions are evaluated, after converted to strings placed into HTML page at the place it occurred in JSP page. Examples of writing Expressions are:

<h2> Time: <%= new java.util.Date() %> </h2>
will print current data & time after converting it to String

 <h2> Welcome: <%= request.getParameter(“name”)%> </h2>
will print the name attribute.


The format of writing a scriptlet is: <%= Java code %>. After opening up the scriptlet tag, any kind of java code can be written inside it. This code is inserted into corresponding servlet. Example of writing a scriptlet is:

String n = request.getParameter(“name”);
out.println(“welcome ” + n);

The above scriptlet reads the name attribute and prints it after appending “welcome”.


The format of writing a declaration tag is: <%! Java code %>.
This tag is used to declare variables and methods at class level. The code written inside this tag is inserted into servlet’s class definition. Example of declaring a class level (attribute) variable is:

private int someField = 5; %>
Example of declaring a class level method is:
public void someMethod ( …… ) {
Writing JSP scripting Elements in XML
Now days, the preferred way for composing a JSP pages is using XML. Equivalent XML tags for writing scripting elements are:

-   Declaration: <jsp:declartion> </jsp:declaration>
-   Expression: <jsp:expression> </jsp:expression>
-   Scriptlet: <jsp:scriptlet> </jsp:scriptlet>

It’s important to note that every opening tag also have a closing tag too. 

Below is an example of jsp file (using XML). It takes 2 parameter and print their summation in response:

<?xml version="1.0" encoding="UTF-8"?>
<jsp:root xmlns:jsp="" version="2.0">
<!-- to change content type change the following line -->
< contentType="text/xml;charset=UTF-8"/>
<!-- any content can be specified here, e.g.: -->
<jsp:element name="text">
int res;
public int sum(int op1, int op2) {
return op1 + op2;
String op1 = request.getParameter("num1");
String op2 = request.getParameter("num2");
int firstNum = Integer.parseInt(op1);
int secondNum = Integer.parseInt(op2);
res = sum(firstNum, secondNum);
<jsp:text> Sum is: </jsp:text>
<jsp:expression> res </jsp:expression>
Implicit Objects
To simplify code in JSP expressions and scriptlets, we are supplied with eight automatically defined variables called implicit objects. The three most important variables are request, response & out. Details of these are given below:

1) Request: This variable is of type HttpServletRequest, associated with the request. It gives access to the request parameters, the request type (e.g. GET or POST), and the incoming HTTP request headers (e.g. cookies etc).

2) Response: This variable is of type HttpServletResponse, associated with the response to client. By using it, we can set HTTP status codes, content type and response headers etc.

3) Out: This is the object of JspWriter used to send output to the client.

4) Session: This variable is of type HttpSession, used to work with session object.

5) Application: This variable is of type ServletContext. Allows to store values in key-value pair form that are shared by all servlets in same web application.

6) Config: This variable is of type ServletConfig. Represents the JSP configuration options e.g. init- parameters etc.

7) pageContext: This variable is of type javax.servlet.jsp.PageContext, to give a single point of access to many of the page attributes. This object is used to stores the object values associated with 'this' object.

8) Exception: This variable is of type java.lang.Throwable. Represents the exception that is passed to JSP error page.

9) Page: This variable is of type java.lang.Object. It is synonym for  'this' .
JSP Directives
JSP directives are used to convey special processing information about the page to JSP container. It affects the overall structure of the servlet that results from the JSP page. It enables programmer to:
-   Specify page settings
-   To Include content from other resources
-   To specify custom-tag libraries

1) JSP page Directive

Give high level information about servlet that will result from JSP page. It can be used anywhere in the document. It can control:
-   Which classes are imported
-   What class the servlet extends
-   What MIME type is generated
-   How multithreading is handled
-   If the participates in session
-   Which page handles unexpected errors etc.

The lists of attributes that can be used with page directive are:
-   language = “java”
-   extends = “package.class”
-   import = “package.*,package.class,…”
-   session = “true | false”
-   Info = “text”
-   contentType = “mimeType”
-   isThreadSafe = “true | false”
-   errorPage = “relativeURL”
-   isErrorPage = “true | false”

Some example uses are:

-   To import package like <%@page import=“java.util.*” info=“using util package” %>
-   To declare this page as an error page: <%@ page isErrorPage = “true” %>
-   To generate the excel spread sheet: <%@ page contentType = “application/” %>

2) JSP include Directive

Lets us include (reuse) navigation bars, tables and other elements in JSP page. We can include files at Translation Time (by using include directive) or Request Time (by using Action elements). Its purpose it to include a file in a JSP document at the time document is translated into a servlet. It may contain JSP code that affects the main page such as response page header settings etc.
<%@include file=“relativeURL”%>

JSP Life Cycle Methods

The life cycle methods of JSP are jspInit(), _jspService() and jspDesroy(). On receiving each request, _jspService() method is invoked that generates the response as well.

No comments:

Post a Comment