Você está na página 1de 17

[JSP(Java Server Pages)]

Monday, August 11, 2014


Why JSP?
Servlet technology is the 1st technology from Sun Microsystems, for creating dynamic
web-applications.
Actually servlet is a good technology, but having a drawback that a lot of java code
needed to create a web-application.
In order to reduce programming code burden on developers, Microsoft introduced ASP
technology.
ASP is a tags based technology. It means instead of writing huge code, tags are provided.
Many developers at industry are attracted for ASP, instead of servlet.
In order to overcome the problems of servlet technology and also to make competition for
ASP, Sun Microsystems releases second technology for creating web-applications as jsp.
What is JSP?
JSP is a page, not a program.
A JSP page consists html and jsp tags.
A JSP is a dynamic web-page, it knows how to process a request and how to create a
response for a request.
Differences between Servlet and Jsp:SERVLET
JSP
In a servlet huge amount of java code is required
In JSP, java code is minimized, due to JSP tags.
If a servlet is modified then we should re-compile it, We can modify the jsp of server, but we no need to rethen re-load it and sometimes we need to restart the compile, re-load or re-start.
server.
In a servlet, we mix business logic and presentation In jsp, we can separate business logic and
logic. So both logics cannot be parallel developing.presentation logic. So parallel development is
(tightly coupled)
possible. (loosely coupled)
By default there is no session behavior in servlet. If In JSP by default there is a session management.
required then we need to attach.
In servlet we have no implicit objects.
In JSP we have implicit objects
In servlet, all protocols request accepted by extending A JSP, only accept http protocol request.
GenericServlet.
Tuesday, August 12, 2014
JSP translation: Every jsp page will be translated into equivalent servlet at server-side.
We are creating a jsp page is nothing but we are creating indirectly a servlet class only.
In order to translate a jsp into an equivalent servlet, a container uses a jsp engine.
From server to server a jsp engine will be different.
For example, In Tomcat or JBoss or Glassfish, the jsp engine is jasper and in Weblogic
server jsp engine is jspc.
A jsp translation consists two parts.
Translation Page.
Service Page.
Translation page means, creating an equivalent servlet and compiling it.
Service page means, creating an object, initializing it and executing service method of

jsp.
When a first request is given to a jsp or when a jsp is modified then both translation page
and service page are executed.
For the remaining request, only service() method of jsp will be executed.
If we shutdown and restart a server then service page is executed.

In translation page, two compiler used


Page Compiler
Java Compiler
Page Compiler converts jsp to servlet.
Java Compiler converts a servlet to .class file.
request
TranslationPage
Service Page
translated
complied
instantiated
Initialized
service
First request

Request 2

----------------------------------JSP Modified Page--------------------------------------------------------------------Request 3

--------------------------------------------Server Restarted-------------------------------------------------------------Request
after

restart
Life cycle methods of JSP: Life cycle methods of jsp are similar to life cycle methods of servlet.
Jsp life cycle methods are
jspInit();
_jspService(HttpServletRequest request, HttpServletResponse response);
jspDestroy();
Wednesday, August 13, 2014
The life cycle methods of jsp are given by javax.servlet.jsp.HttpJspPage interface.
An implementation class of HttpJspPage interface will be given by a server vendor. So
the implementation class will be changed from one server to another server.
At the time of translating a jsp page to an equivalent servlet (JES), a container extends
that internal servlet class from the implementation class given by the vendor.
For example, in case of Tomcat server, the implementation class given for HttpJspPage
interface is HttpJspBase class. So a container extends HttpJspBase class internally.
The implementation class given by vendor will be an abstract class and at the time of

extending that class a container overrides its abstract method called _jspService() into
JES.
In every server, the implementation class given by a vendor contains _jspService()
method as abstract method and it is overridden by a container at translation time.
The implementation by a vendor also extends HttpServlet. So a JES indirectly extending
HttpServlet.
For example, In Tomcat server HttpJspBase class extend HttpServlet and implements
HttpJspPage interface.
Like servlet life cycle, jsp life cycle methods jspInit() and jspDestroy() are executed for
once and _jspService() method will be executed for each request.
The service method of jsp is started with _ symbol, to indicate that service method
should not be overridden by a jsp programmer.
In jsp life cycle methods, jspInit() and jspDestroy() can be overridden by a
programmer, but _jspService() method cannot be overridden.
Configuration of Jsp: Jsp page is a public file of a web application. So it can be directly requested from browser
with file name.
Note:- In a web application, the files which are stored under root directory are called
public files. For example, html, jsp, images etc.
The remaining files of a web application are called private file.
Configuring a jsp page in web.xml is optional. It means, if we configure a jsp then we can
send request from browser either with file name or with url pattern.
If a jsp is not configured in web.xml then we can send a request only with the file name
from a browser.
Jsp configuration is almost equal to a servlet configuration only. The only one difference
is, replace <servlet-class> tag with <jsp-file> tag.
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<jsp-file>/a.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/j1</url-pattern>
</servlet-mapping>
</web-app>
Scripting elements of JSP: Scripting elements are used to insert java code into the jsp page.
Scripting elements are divided into 3 types.
scriptlet
expression
declaration
scriptlet: This tag is used for inserting java code into jsp page, which we want to run for each
rquest.
scriptlet tag can be written in a jsp page either in html syntax or in xml syntax.
<%

java code
%>
This comes under html syntax
<jsp:scriptlet>
java code
</jsp:scriptlet>
This comes under xml syntax
At the time of translating the jsp into servlet, a java code written in scriptlet tag will be
inserted into _jspService() method. So a scriptlet tag code will be executed for each
request.
A jsp page contain any no of scriptlet tag.
If we declare any variables under scriptlet tag then they become as local variables to the
_jspService() method at translation time.
Example1:-

In a scriptlet tag, method definitions are not allowed. Because at translation time, the
method goes to _jspService() mehthod, but java does not allow one method definition in
another method.
For example,

This is invalid
Thursday, August 14, 2014
expression tag: An expression tag is used to find the result of an expression and to print that result on
browser for each request.
An expression tag can be writtern in a jsp page in two ways.
<%=
expression
%>
This comes under html syntax
<jsp:expression>
expression

</jsp:expression>
Every expression tag will be first translated to out.print statement and then that statement
will be inserted to _jspService() method. So an expression tag will be executed for each
request.
For example,
a.jsp
----<%
int a=100, b=200;
%>
<%=
a*b;
%>

a_jsp.java
public class a_jsp extends HttpJspBase
{
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
int a=100;
int b=200;
out.print(a*b);
}
}
expression tag
translated code
valid/invalid
<%= int x=100; %>
out.print(int x=100;);

<%= c=a+b %>


out.print(c=a+b);

<%= a,b %>


out.print(a,b);

<%= a+b; %>


out.print(a+b;);

<%= out.print(a) %>


out.print(out.print(a));

<%= this.x+this.y %>


out.print(this.x+this.y);

<%= for(int i=1; i<=5; i++){}%> out.print(for(int i=1; i<=5; i++){});

declaration tag: This tag is used to create/define global variables or methods in a jsp page.
At translation time, the variables and methods of a declaration tag goes to class, not to
service method.
A declaration tag can be written in 2 ways
<%! declaration %> ---- html syntax
<jsp:declaration> declaration </jsp:declaration> --- xml syntax.
A declaration tag of jsp will be executed for once.
Example1:a.jsp
----<%!
int a=10;
%>
<%

int b=20;
%>
a_jsp.java
public class a_jsp extends HttpJspBase
{
int a=10; //instance/global variable
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException
{
int b=20; //local variable
}
}
Example 2:
a.jsp
----<%!
public String sayHello()
{
return "Hello";
}
%>
<%
String s= sayHello();
out.print(s);
%>
a_jsp.java
----------public class a_jsp extends HttpJspBase
{
public String sayHello()
{
return "Hello";
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String s = sayHello();
out.print(s);
}
}
Q. Can we write a static method in a declaration tag or not ?
Ans: Yes.
a.jsp
----<%!
public static String sayHello()
{
return "Hello";
}

%>
<%
String s = a_jsp.sayHello();
out.print(s);
%>
Q. Can we use implicit object of jsp in a declaration tag?
Ans: No, implicit objects are available only for the code which goes to _jspService() method, but
not to the code goes to the class.
<%!
public void sayHello();
out.println(Hello);
%>
This is invalid statement. Because out is an implicit object, not allowed in declaration tag.
<%
out.println(Hello);
%>
This is valid.
Friday, August 15, 2014
Q. Which tag of jsp is required to override life cycle init and destroy methods of a jsp?
Ans: declaration tag.
a.jsp
-----<%!
public void jspInit()
{
}
public void jspDestroy()
{
}
%>
Q. Can we override servlet life cycle methods in a jsp page?
Ans: No. Reason is at the time of translating a jsp to servlet, the super class given by server made
servlet life cycle method as final. A super class final method cannot be overridden in sub class.
For example, In Tomcat server, HttpJspBase is the super class of JES and it made servlet life
cycle methods as final. So we cannot override final method in sub class.
Q. Can we write interfaces and classes in a jsp page or not?
Ans: YES. If we write an interface or a class in declaration tag then that code goes to class at
translation time. In java we can write an interface with in a class and a class with in a class. So it
is possible.
Comments in JSP: In a jsp we can add 3 types of comments.
Html Comment.
Jsp Comment.
Java Comment.
Html and Jsp comments are allowed directly in a page but not allowed in a declaration or
a scriptlet tag.
<!-- Comments --> ----- html comment tag.
<%-- Comments --%> ----- jsp comment
Expression tag of jsp doesnt allow comments.

Declaration tag and scriptlet tag allows only java comments.


<%
//local variable ----- allowed
int x = 10;
<%-- local variable2 --%> ----- not allowed
int y =20;
<!-- local variable3 --> ----- not allowed
int z = 30;
%>
After translation, in JES html and java comments are visible in _jspService() method. But
jsp comments are invisible. So we call jsp comment as hidden comment.
Html comments come to browser along with response. So we can see html comment on
the browser by opening view source of the page.
Example1:
The following jsp page counts no of request comes from browser
http://localhost:3488/JspApp1/a.jsp
In tomcat server, internal servlet (JES) can be seen at the following location.
C:\Program File\Apache Software Foundation\Catalina\localhost\JspApp1\org\apache\jsp
Q. How a container identifies whether a jsp page is modified or not?
Ans:
A container internally use a file comparison tool that tool tells container whether a jsp page is
modified or not.
For example, Tomcat uses a file comparison tool internally araxis.
Wednesday, August 20, 2014
In the following example, we want to communicate from html to jsp.

Esample: JspApp2-------------------------------------..
Jsp Directives: Directives of jsp are not used for inserting any java code and not used for generating
output to the browser.
Directives are used to give some direction to the container, to be followed at translation
time.
In jsp, we have 3 directives:
include
page
taglib
include directive:-

This directive tag tells container that, include source code of one file to another at the
translation time.
We can write this directive tag in html and xml syntax like the following:
<%@ include file="B.jsp" %> ------- html syntax
<jsp:directive.include include file="B.jsp" /> ------- xml syntax
This include directive tag includes source code of a destination file to a source file. After
that, if any changes are done in the destination file, then they are not affected/reflected in
the source file. So this is called compile-time/static including.
We can include the source code of multiple destination files into a single source file.
A destination file can be either html or a jsp page.
page directive: This directive is to set an important behavior for a jsp page like session management,
error page handling, buffer etc.
We can write this page directive either in html or in xml syntax.
<%@page attributes%> ------------ html syntax
<jsp:directive.page attributes%> ----------- xml syntax
session:
This attribute either enables or disables session management in jsp.
The default value of this attribute is true. It means by default sessions are enabled in
jsp.
If we want to disable, session management in jsp then we need to add the page
directive like the following:
<%@page session=false%>
If the session management is disabled then it cannot use session object (implicit
object /readymade object) in that page.
import:This attribute is used for importing a pre-defined or user-defined java package in to a
jsp page.
In a jsp page, a package can be imported at anywhere in the page. It means, either at
on top or at bottom, or at middle of the page.
At translation time, container will collect all import attribute and imports at top of the
servlet.
We can import multiple packages by separating with , or we can repeat import
attribute for multiple times in a jsp page.
Among multiple attributes of page directive, the only one attribute which is
repeatable with different values is import.
<%@page import="java.util.*"%> ----- valid
<%@page import="java.util.*","java.sql.*"%> ------ valid
<%@page import="java.util.*" import="java.sql.*"%> ------ valid
<%@page import="java.util.*"
import-"java.util.*"%> ------ valid
<%@page import="java.util.*"%>
--------------------------------------------------------<%@page import="java.sql.*"%> ----- valid
language:This attribute is used for setting language to be used in the scripting elements.
The default value and the only available value is java.

<%@page language="java"%>
isThreadSafe:This attribute tells a container whether multiple threads are allowed concurrently or a
single thread is allowed concurrently to access a jsp page.
The default value of isThreadSafe is true. It means multiple threads are allowed
concurrently to access a page.
If we write isThreadSafe=false, then one thread allowed at a time to access a jsp
page.
If we write isThreaSave=false, then at the time of translation, a container
implements internal servlet class (JES) from SingleThreadModel interface.
Thursday, August 21, 2014
errorPage:This attribute is to tell the container that, send the control to another page, if an
exception is occurred in the current page at the runtime.
If only exception occurs then the control will be transferred otherwise not transferred.
For example,
a.jsp
---------------<%@page errorPage="error.jsp"%>
isErrorPage:The default value of isErrorPage attribute is false.
By default, a jsp page does not act as an error page. Because by default isErrorPage =
false.
If we want to make a jsp page as an error page, then we should set isErrorPage =
true.
If a jsp page is acting as error page, then exception object is allowed to use in that
page.
For example,
error.jsp
----------<%@page isErrorPage="true"%>
contentType:This attribute is to set MIME type of the response.
The default value of this attribute is text/html.
In a jsp page, contentType can be set in 2 ways.
Using contentType attribute.
By calling setContentType() method.
<%@page contentType="text/xml"%>
<%
response.setContentType("text/xml")
%>
buffer:In jsp, we use an implicit object is called out, for sending response to the browser.
out is an implicit object of class JspWriter.
By default, out object maintains a buffer (cache) and the statements are stored in that
buffer first. Later from buffer the data will be transferred to the response object.
In servlet, we use PrintWriter class object and it directly writes the response data into
response object.

The advantage the buffer in the middle, it reduces the no. of inter actions with the
response object. So it improves performance.
If you want to increase or reduce or remove a buffer then we use buffer attribute.
The default value of buffer attribute is 8kb.
If buffer is removed, then PrintWriter and JspWriter classes, both becomes equal.
<%@page buffer="15KB"%>
<%%page buffer="none"%>
autoFlush:This attribute is used to either enable or disable flush mode in jsp.
The default value of this attribute is true. It means autoFlush mode is enabled.
When autoFlush mode is enabled then a container will automaticlay flush a buffer, when
it is full or when it is close.
Flushing a buffer means, transferring the data to the response object and clearing it from
the buffer.
If autoFlush mode is disabled, then a programmer has to call flush() method explicitly to
flush the buffer.
If a programmer calls flush() method after a buffer is full then BufferOverFlow
exception will be thrown.
Info:This attribute is used for writing a page level readable comment.
If this attribute is added in jsp page, then at translation time, a container will created
gerServletInfo() method in JES.
We can read the message of info attribute by calling getServletInfo() under scriptlet tag of
jsp.
a.jsp
--------------<%@page info="A sa,ple message"%>
<%
String str=getServletInfo();
%>
extends:This attribute tells a container to extend the internal servlet from a given class.
If we want to set our class name as a super class for the internal JES then first we need to
create our class by extending HttpServlet and by implementing HttpJspPage interface.
<%@page extends=com.satya.servlet.MyServlet%>
public class MyServlet extends HttpServlet implements HttpJspPage
{}
Attribute
Default value
session
true
Import
Language
java
isThreadSafe
true

errorPage
isErrorPage
contentType
Buffer
autoFlust
Info
Extends

none
text/html
8kb
True
-

Friday, August 22, 2014


Standard actions in JSP: The actions tags of jsp are used for communicating a jsp with another jsp or a servlet or
an applet or a java bean.
The action tag of jsp follows only xml syntax.
We have 9 action tags in jsp.
<jsp:forward>
<jsp:incllude>
<jsp:param>
<jsp:params>
<jsp:plugin>
<jsp:fallback>
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:forward>: This action tag is used for forwarding a request from a jsp to another jsp or a servlet or a
html.
Generally, if a huge logic is required in a jsp then we divide that logic into multiple jsp
pages and then we apply forwarding technique.
If destination is a jsp or html then file name is required and if destination is a servlet then
url pattern is requied.
<jsp:forward page="/srv1"/>
<jsp:forward page="b.jsp"/>
<jsp:forward page="index.html"/>
When a request is forwarded then along-with the request, automatically request
parameters send from browser or also forwarded. If you want to attach additional
parameters then we use <jsp:param> tag inside <jsp:forward> tag.
<jsp:forward page="b.jsp">
<jsp:param name="p1" value="10"/>
<jsp:param name="p2" value="20"/>
</jsp:forward>
In the following example, we are using jsp to servlet application by forwarding a request.
ForwardTest
WEB-INF
web.xml
classes
SalaryServlet.java
index.html

Program:---------------<jsp:include>
This action tag is used for including the response of one resource like a jsp or a servlet or
a html into another jsp page.
In jsp, we have two types of including,
include directive
include action
include directive is for static including and include action is for dynamic including.
Internally a container uses RequestDispatchers include method, for executing
<jsp:include> tag.
************ We choose include directive when a destination is a static page like html
and we choose include action, when a destination is a dynamic resource like a jsp or a
servlet.
Saturday, August 23, 2014
<jsp:plugin>
This action tag is given for integrating a jsp page with an applet.
When a jsp wants to display response in a graphics format in a browser, then a jsp page
will integrates with an applet.
In applet class, we have a method called paint(). In this method we can create output in
graphical format using methods of Graphics class.
<jsp:plugin type="applet" code="classsname" width="200" height="200">
<jsp:paarams>
<jsp:param ----------/>
<jsp:param------------/>
</jsp:params>
<jsp:fallback>Alternate Message</jsp:fallback>
</jsp:plugin>
<jsp:useBean>
This standard action tag is to establish a connection between a jsp page and a java bean.
In web applications of java, jsp and java bean communication is required in the following
two cases:
In a real-time MVC project, a model class (business class) will set the data to a
java bean and a jsp (view) will read the data from a bean and finally displays it on
the browser. In this class jsp to a java bean communication is required.
If multiple jsp pages need common java logic then it separates that java code into a
bean and then we call the bean from jsp. In this case also jsp to java bean
communication is required.
<jsp:useBean> tag is used for creating an object of a bean class in a jsp page.
<jsp:useBean id ="object name" class="fully qualified class"
scope="page/request/session/application"/>
Monday, August 25, 2014
Every java class is not a java bean class automatically. A class should have the following
quality, to make it as a java bean.
Class must be a public.
Class must contain a default constructer
Every private property of the class must contain either setter or getter or both

methods.
A class can at-most implement Serializable interface.
<jsp:setProperty>
This action tag is to set input value to a property/variable of a bean class, by calling setter
method of the property.
When a request comes from browser, the protocol is http and it doesnt known for the
java bean. So directly input values from browser cannot be send to a java bean.
The flow of setting input values is, a jsp page takes request from browser and it will set
input values to bean using <jsp:setProperty> tag.
<jsp:setProperty> tag must be used inside <jsp:useBean> tag.
<jsp:setProperty> tag contains 4 attributes.
name Object name . The value of this attribute must be same as the value of id
attribute in <jsp:useBean> tag.
property variable name in bean class.
param request parameter name
value a static value
Name and property attributes are mandatory. We should not use param and value
attribute at a time.
If request parameter names and variable names in bean class are matched, then we can
directly write property=*.
name, property, value allowed
name, property, param allowed
property, param not allowed
name, property, value, param not allowed
<getProperty>
This action tag is used to read the value of a variable of a bean class by calling its getter
method. This action tag must be written at outside of <jsp:useBean> tag.
This action tag only has two attribute called name and property.
In this tag property=* is not allowed.
Applicttion:
In the following example, we are verifying username and password using jsp to bean
communication.
--------------------------Tuesday, August 26, 2014
Bean Scopes
page scope: It is the default scope for a bean object.
If page scope is set for a bean object, then it is not sharable with other pages in the
application.
We call this page scope as local scope.
<jsp:useBean id=obj1 class=p1.DemoBean scope=page/>
request scope: If request scope is set for an object, then that object becomes sharable to other jsp pages
which are participating in the current request.
The life time of request scope ends whenever response for the request is sent for the

browser.
<jsp:useBean id=obj1 class=p1.DemoBean scope=request/>
session scope: If session scope is set for an object, then it becomes sharable to all other jsp pages visited
by the same client with in the session of that client.
In web applications, each client has one session and it will be destroyed, when a client
logout or when its expiry time is reached.
<jsp:useBean id=obj1 class=p1.DemoBean scope=session/>
application scope: This is the global scope of a web application.
If application scope is set for an object then it becomes sharable in all other pages for all
the clients of web application.
<jsp:useBean id=obj1 class=p1.DemoBean scope=application/>
Example of Bean Scope
-----In the following example, jsp page gets image name from bean and then displays that image on
browser with the help of <img> tag. The images are rotated on the browser for each 5 seconds.
Wednesday, August 27, 2014
JSP implicit object: In JSP, we have 9 implicit objects.
request -- javax.servlet.http.HttpServletRequest(I)
response -- javax.servlet.http.HttpServletResponse(I)
out -- javax.servlet.jsp.JspWriter(C)
session -- javax.servlet.http.HttpSession(I)
exception -- javax.lang.Throwable(C)
config -- javax.servlet.ServletConfig(I)
application -- javax.servlet.ServletContext(I)
page -- javax.lang,Object(C)
pageContext -- javax.servlet.jsp.PageContext(AC)
request: This implicit object is used in a jsp page to do the following.
To read request parameters.
To read cookies sent from browser.
To read headers etc.
Example1:
<%
String s1 = request.getParameter(uname);
%>
Example2:
<%
Cookie cookies[] = request.getCookies();
%>
Example3:
<%
String str = request.getHeader(User-Agent); // str it stores browser name
%>
response: This object is used in a jsp to do the following:

To set the MIME type for a response.


To send cookies to the browser.
To redirect a request from one jsp to another resource etc.
Example1:
<%
response.setContentType(text/xml);
%>
Example2:
<%
response.addCookie(c1);
%>
Example3:
<%
response.sendRedirect(classname.jsp);
%>
session: This object is available in a page, if session attribute of page directive is true.
For using this session object, we can read session information or we can share a value
with in the session scope.
Example1:
<%
out.println(session.getId());
out.println(session.getMaxInactiveInterval());
%>
Example2:
<%
session.setAttribute(k1,Java);
%>
exception: This object captures exception occurred in another page at runtime.
For example,
//a.jsp
<%@page errorPage=b.jsp%
//b.jsp
<%@ page is ErrorPage=true%>
<%=exception%>
If an exception is occurred in a.jsp, then that exception is printed on the browser by b.jsp

Você também pode gostar