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
1-In a servlet huge amount of java code is required
2-In JSP, java code is minimized, due to JSP tags.
3-If a servlet is modified then we should re-compile it, then re-load it and sometimes we need to restart the server.
We can modify the jsp of server, but we no need to re-compile, re-load or re-start.
4-In a servlet, we mix business logic and presentation logic. So both logics cannot be parallel developing. (tightly coupled)
In jsp, we can separate business logic and presentation logic. So parallel development is possible. (loosely coupled)
By default there is no session behavior in servlet. If required then we need to attach.
5-In JSP by default there is a session management.
6-In servlet we have no implicit objects.
7-In JSP we have implicit objects
8-In servlet, all protocols request accepted by extending GenericServlet.
9-A JSP, only accept http protocol request.
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 and in Weblogic server jsp engine is .
-
A jsp translation consists two parts.
-
1-Translation Page.
-
2-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
-
1- Page Compiler
-
2- Java Compile
-
Page Compiler converts jsp to servlet.
Java Compiler converts a servlet to .class file.
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();
-
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
<weeb-app>
<servlet>
<servlet-name>fist</servlet-name>
<jsp-file>a.jsp</jsp-fle>
</servlet>
<servlet-mapping>
<servlet-name>fist</servlet-name>
<url-pattern>/url<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.
1- scriptlet
2- expression
3- 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.
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.
example
a.jsp b.jsp
<% public class a_jsp extends HttpJspBase
for(int i=0;i<=10;i++) {
{ public void _jspService(HttpServletRequest req,HttpServletResponse res)throws SE,IOE
sum=sum+i; {
} for(int i=0;i<=10;i++)
%> {
sum=sum+i
}
}
}
-
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.
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.
Syntax:-
<%=
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,
<%
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;); X
<%= c=a+b %> out.print(c=a+b); X
<%= a,b %> out.print(a,b); X
<%= a+b; %> out.print(a+b;); X
<%= out.print(a) %> out.print(out.print(a)); X
<%= this.x+this.y %> out.print(this.x+this.y); correct
<%= 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 taggoes 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.
Example:-
<%!
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) throwsServletException, 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) throwsServletException, 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.
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.
1 -Html Comment.
2 -Jsp Comment.
3 -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 doesn’t allow comments.
-
Declaration tag and scriptlet tag allows only java comments.
<%
//local variable ----- allowed
int x = 10;
<%--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.
In the following example, we want to communicate from html to jsp.
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:
1- include
2-page
3-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
1-session
2- import
3- language
4- isThreadSafe
5- errorPage
6- isErrorPage
7- contentType
8- buffer
9- autoFlush
10- Info
10- extends
1-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.
2-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
3-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"%>
4-isThreadSafe:-
This attribute telhe default value of isThreadSafe is “true”. It means multiple threads are allowed concurrently to access a page.If we write thenls a container whether multiple threads are allowed concurrently or a single thread is allowed concurrently to access a jsp page.T one thread allowed at a time to access a jsp page.
5-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,
%@page errorPage="error.jsp"%>
If we write , then at the time of translation, a container implements internal servlet class (JES) from SingleThreadModel interface.
6-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,
<%@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/html");
%>
8-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"%>
9-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.
10-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();
%>
11-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
{}
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 servletthen 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:forword>
In the following example, we are using jsp to servlet application by forwarding a request.
<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,
1- include directive
2- include action
-
include directive is for static including and include action is for dynamic including.
-
Internally a container uses RequestDispatcher’s 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.
<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:param>
<jsp:param ----------/>
<jsp:param>
</jsp:params>
<jsp:fallback>Alternate Message</jsp:fallback>
<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"/>
-
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 doesn’t 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=”*”.
1- name, property,value --> allowed
2- name, property, param --> allowed
3- property, param -->not allowed
4- 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.
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.
JSP implicit object:-
-
In JSP, we have 9 implicit objects.
1- request -- javax.servlet.http.HttpServletRequest(I)
2- response -- javax.servlet.http.HttpServletResponse(I)
3- out -- javax.servlet.jsp.JspWriter(C)
4- session -- javax.servlet.http.HttpSession(I)
5- exception -- javax.lang.Throwable(C)
6- config -- javax.servlet.ServletConfig(I)
7- application -- javax.servlet.ServletContext(I)
8- page -- javax.lang,Object(C)
9- 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
Example:-
<%
out.println(session.getId());
out.println(session.getMaxInactiveInterval());
%>
exception:-
-
This object captures exception occurred in another page at runtime.
For example,
-
-
%@page errorPage=”b.jsp”%
-
<%@ page is ErrorPage=”true”%>
-
If an exception is occurred in a.jsp, then that exception is printed on the browser by b.jsp
JSP(java server page)
