the java server pages
DESCRIPTION
The descriptive and practical approach to Java Server Page Technology.TRANSCRIPT
ByAtul SaurabhAssist. ProfessorBITs edu Campus
THE JAVA SERVER PAGES
JSP is basically used to generate dynamic web pages.
In layman language JSP can be defined as “JSP is a HTML fi le embedded with JAVA code”.
Inside JSP one can write HTML for static content and JAVA code for dynamic content.
WHAT IS JSP…LAYMAN DEFINITION
Technically a JSP is defined as follow :
“A JSP is a server side technology running in a special engine called JSP engine , providing dynamicity to the web pages and works as a high level abstraction to the java servlet”.
A JSP page is basically an extension to the Java Servlet technology. JSP contains both HTML and JAVA code. When a JSP is compiled, it is transformed into JAVA Class. This transformation is done by a special compiler called Page Compiler.
WHAT IS JSP …TECHNICAL DEFINITION
A JSP, when transformed into JAVA class, extends org.apache.jasper.runtime.HttpJspBase class. Here is the class hierarchy
CLASS HIERARCHY OF JSP
org.apache.jasper.runtime.HttpJspBase
javax.servlet.jsp.HttpJspPage
javax.servlet.jsp.JspPage
javax.servlet.ServletI
I
I
C
extends
implements
From the hierarchy it is very clear that any JSP page is nothing but a Servlet. The HttpJspBase class provides all the implementation to each abstract methods. Here is the declaration of HttpJspPage interface.
package javax.servlet.jsp;public interface HttpJspPage extends JspPage{ public void _jspService(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException;}
DETAILS OF HIERARCHY
CONTD…
Here is the declaration of JspPage interface.
package javax.servlet.jsp;
public interface JspPage extends Servlet{ public void jspInit() throws JasperException; public void jspDestroy();}
Whenever a JSP page is created, the server also create a c lass for that JSP page. And the server only runs that c lass whenever a request comes for that JSP. So here is the code for the c lass:
import javax.servlet.http.*;import javax.servlet.*;import org.apache. jasper.runtime.*;publ ic c lass MyJsp extends HttpJspBase{ publ ic void jspInit() throws JasperException { / / Code to init ia l ize JSP } publ ic void _ jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { / / Code for business logic }}
JSP PROGRAMMATICALLY
The life cycle of JSP is very similar to Servlet.
LIFE CYCLE OF JSP PAGE
Receive
Request
Is JSP loaded
Call jspDestroy
Call init
Call jspInit
Call service
Call _jspService
NO
yes
No req for long time
The syntax of JSP is consists of the following components.
NUT AND BOLT OF JSP
JSP Syntax
DirectiveScripting Elements
Action Elements
@page
@include
@taglib Scriptlet
Declaration
Expression
Action Tags
Custom Tags
The directives are generally used to change the behavior of the current JSP page. All the directive are written in the following general form
<%Directive_name (attribute=value)*%>
Note : Here (attribute=value)* means zero or more attributes is possible.
As for example : If we need to use @page directive with language attribute then the syntax will be
<%@page language=“java”%>
THE DIRECTIVE
The @page directive normally controls the behavior of the class generated for the current JSP page, as we know the server always generates a class for each and every JSP. Here are the list of attributes and their purpose.
@PAGE DIRECTIVE
No.
Attribute Name
Description Default Value
1. language Scripting Language Name
Java
2. contentType
MIME Type, Character set
Text/html;charset=ISO-8859-1
3. extends Generated jsp class will extends the given class
None
4. import Generated jsp class will import the package
None
5. session The generated class will participate in session
true
Here is an example of @page directive.Let us suppose we are having a jsp page with name MyJsp. Now
<%@ page import=“java.util.*” %><%@ page extends=“MyNewJspWrapper” %>
The above written code is converted into following jsp class
EXAMPLES
1
2
import java.util.*;import org.apache.jasper.runtime.*;public class MyJsp extends MyNewJspWrapper{ // other useful methods}
CONTD…
1
2
The @include directive is used to include the content of some other fi le in the current fi le. Here is an example.
@INCLUDE DIRECTIVE
<html> <body> <%@include file=“test.txt” %></body></html>
ABC.jsp
Here is the content of test.txt
Here is the resulting jsp page
CONTD…
<b> Hello What are you doing </b><%int a = 10;%>
<%=a%>
<html> <body>
<b> Hello What are you doing </b><%int a = 10;%>
<%=a%></body></html>
When the resulting JSP is run the following output is shown
The include directive never process the fi le which is to be included. It only include the content and NOT the output of the fi le.
CONTD…
Hello What are you doing 10
Scripting elements provides great power to JSP Pages
The scripting element is used to add dynamicity to the JSP pages.
All the scripting element has predefined location to place inside the generated JSP class.
THE SCRIPTING ELEMENT
The Declaration scripting element is denoted by <%! %>. The code written inside the declaration becomes the member of the generated JSP class. So, we can declare methods and fi elds inside the declaration.Here is an example:
THE DECLARATION
<%! int myAge=10; private int calculateBirthDate(int age) { return 1988 – age; }%>
A
B
Here is the code for generated JSP class.
CONTD…
import org.apache.jasper.runtime.*;public class MyJsp extends HttpJspBase{ int myAge=10; private int calculateBirthDate(int age) { return 1988 – age; }
}
A
B
The myAge and calculateBirthDate become the member of the
class MyJsp
Any processing instruction can not be written inside the declaration tag.
This will give a compilation error. The processing instruction must go inside some method.
CONTD…
<%! System.out.println(“Hello World”); %>
Wrong
The scriptlet tag is denoted by <% %>. The scriptlet tag is nothing but a part of _jspService() method defined earlier. Any code written inside <% %> will be copied inside the _jspService() method.
THE SCRIPTLET
<% int myAge=10; out.println(“Hello everyone, My age=“+myAge);%>
1
The previous code is translated as follows:
CONTD…
public class myJsp extends HttpJspBase{ public void _jspService(HttpServletRequest request, HttpServlerResponse response) throws ServletException, IOException { int myAge=10; out.println(“Hello everyone, My age=“+myAge); }
}
1
We can define any variable inside <% %>. As for example in previous code myAge is defined. The declared variable become the local variable of _jspService() method. Again we can not define any method inside <% %> as we can not define a method inside a method.
CONTD…
<% public void sayHello() { System.out.println(“Hello world”); }%>
Wrong
But yes we can call any method from <% %>.
CONTD…
<%! public void sayHello() { System.out.println(“Hello World”); }%>
<% sayHello(); %>
Permitted
When the page compiler translate a jsp fi le into JSP class it automatically declares some of the variables inside _jspService() methods. These variables are known as implicit object and are readily available inside <% %> tag only. Keep it mind that the code written inside <%%> is copied inside _jspService() method. The implicit object can be directly used inside <%%> and have fixed names. The declaration of these variable by programmer is not required.
IMPLICIT OBJECTS
<% out.println(“hello world”); %>
No need to define out as it is an implicit object
Here are the list of implicit objects
CONTD…
Sl. No.
Implicit objects Type Purpose
1. request javax.servlet.http.HttpServletRequest
It represent the request send by the client
2. response javax.servlet.http.HttpServletResponse
It represent the response for client
3. out javax.servlet.jsp.JspWriter
User to write on client side
4. session javax.servlet.http.HttpSession
Represent the session for the client
Sl. No.
Implicit objects Type Purpose
5. application javax.servlet.ServletContext
Represent the runtime environment for JSP
6. config javax.servlet.ServletConfig
Represent the configuration for JSP
7. pageContext javax.servlet.jsp.PageContext
Represent the JSP PageContext class
8. page javax.servlet.jsp.HttpJspBase
Represents the JSP page itself.
9. exception java.lang.Throwable
Represent any exception .
CONTD…
The names of implicit object is controlled by page compiler. So we can not use diff erent name.
The exception object is an exception. It is not available on each JSP page. This object is available only if the isErrorPage attribute of @Page directive is true.
CONTD…
<% exception.printStackTrace(); %>
Error… isErrorPage is not true
But
CONTD…
<%@page isErrorPage=“true” %><% exception.printStackTrace(); %>
OK…
The expression tag is represented by <%=%>. It is basically the short form of out.println();. Note the last semicolon. So if we write
The code is translated as
Also the code must be copied inside the _jspService() method.
THE EXPRESSION
<%=“Hello World”%>
out.println(“Hello world”);
So,
CONTD…
<%=“Hello World”%>
public class myJsp extends HttpJspBase{public void _jspService(HttpServletRequest request, HttpServlerResponse response) throws ServletException, IOException { out.println(“Hello World”); }
}
Translated
To write the JSP program we need to follow these steps:1. Create the directory structure Test | |------------WEB-INF |-----------web.xml |-----------classes |------------lib |---------index.jsp
WRITING THE FIRST JSP
2. Content of index.jsp
CONTD…
<%! int myAge=10; public int ageCalculate(int age) { return 1988-age; }%><% int p=ageCalculate(30); %>
<%=p%>
3. Deploy the project inside %CATALINA_HOME%/webapps
4. Run the server %CATALINA_HOME%/bin/startup.bat
5. Run the project
http://localhost:8080/Test
CONTD…
JSP technology provides a great tool. We can define our own tags that can be used at any JSP page and do the custom work not available before. Normally a designer is not a programmer. So writing java code is diffi cult for them. But tags are pretty familiar to them and they can use the tag without knowing how it works. So defining custom tags solves two problems:
1. Gives designers a uniformity and keep them away from coding.
2. Enables custom behavior which is not present into HTML.
THE CUSTOM TAG
The custom tag is written in the following form
INTRODUCTION TO TAG
<myTag:print message=“hello world”>What is the time ?</myTag:print>
prefix
suffix
Start tag
attribute
Value to attribute
body
End tag
Whenever a tag is encountered by run time mechanism of JSP it basically creates an instance of a class. And then call appropriate method from the class. This class is called tag handler class.1. The fi rst step is to create a class which will
implement javax.servlet.jsp.tagext.Tag interface.
DEVELOPING FIRST CUSTOM TAG
import javax.servlet.jsp.*import javax.servlet.jsp.tagext.*;public class myTag implements Tag{
}
The Tag interface has following abstract methods
public int doStartTag() public int doEndTag() public void setPageContext(PageContext p) public void setParent(Tag t) public Tag getParent() public void release()
CONTD…
The JSP container obtains the instance of tag handler from the pool or creates a new one. It then calls setPageContext() method and passes the object of type PageContext. The PageContext represents the environment in which the page is running.
The JSP container then calls the setParent() method if there is any tag represents the role of parent in the tag hierarchy.
The JSP container then set all the attributes for the tag. The attribute is just like a setter-getter method defined inside the handler class.
Now the container calls the doStartTag() tag. The following are the return value of this method.
LIFE CYCLE OF TAG HANDLER CLASS
CONTD…
The container then calls the doEndTag() method. The method must return one of the following value.
Finally the JSP container class the release() method.
Sl. No.
Return Value Description
1. SKIP_BODY The JSP container will skip the tag body
2. EVAL_BODY_INCLUDE
The JSP container will process the tag body
Sl. No. Return Value Description
1. EVAL_PAGE The JSP container will process the rest part of the current JSP page
2. SKIP_PAGE The JSP container will not process the rest part of the current JSP page
2. So the class is defined as follows
WRITING THE CUSTOM TAG CONTD..
public class myTag implements Tag{ private PageContext pageContext; public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } public void setParent(Tag parent) { } public void release(){}
CONTD…
public Tag getParent() { return null;} public void doStartTag() { return SKIP_BODY;}public void doEndTag() { JspWriter out=pageContext.getOut(); out.println(“Hello world”); return EVAL_PAGE; }}
TLD is short form Tag Library Descriptor. The tag processor fi rst read the TLD to get information about the tag. One TLD may contain information about a set of tags. Every TLD is identified by a unique URL. Here is an example :
DEFINING TLD
<taglib> <tlib-version>1.0</tlib-version> <short-name>taglib</short-name> <uri>/WEB-INF/tlds/taglib</uri> <!– TAG CONFIGURATION --> <tag> <name>myTag</name> <tag-class>db2admin. myTag </tag-class> </tag></taglib>
The tld will identified by this
URI
The suffix of the tag
The complete path of Tag Handler class
A
B
TLD must be kept inside WEB-INF director. It may possible that we can place TLD in some folder inside WEB-INF.The tag is configured on JSP page by using @taglib
directice.The following are the attribute of this directive
THE @TAGLIB DIRECTIVE
Sl. No.
Attribute Description
1. uri This identifies which TLD will be used to get information about the tag
2. prefix To define the prefix of the tag
The next step is to use the tag. To use the tag fi rst it must be configure by the @taglib directive and then use the tag on a JSP page.
CONTD…
<%@taglib uri=“WEB-INF/tlds/taglib” prefix=“c” %>
<c:myTag></c:myTag>C
CA
B
Than
k Yo
u