JSP - Java Server Pages
Introduction to JSP
JSP stands for Java Server Pages. JSP is a server side web technology like Servlet. JSP is extension of Servlet not enhancement of Servlet. It does not replace the servlet technology and can be used with Servlets. JSP is used to develop server side web components to generate and render dynamic contents
- JSP is Java code embedded in HTML
Such design (Java with in HTML) allows smooth development of presentation layer. A UI designer/developer can develop HTML pages that are rich in UI feature. A Java developer can later easily embed JSP within these HTML pages. In case of servlets all the HTML contents should be embedded in Java. To achieve rich UI feature, servlets become more of HTML than java. Any change in UI, enforces change in Java code. Change in Java code needs compilation of Java file. This becomes more expensive
- JSP file extension must be .jsp
Basic example of JSP
The typical request-response flow is depicted for JSP
- User sends request to the server from index.jsp
- Server receives the request and directs it to
LoginServlet.java
as per the URL pattern configuration - LoginServlet.java fetches data from request parameters, performs business logic, sets the data in request attributes and forwards the request to welcome.jsp. Not a single line of code to prepare the presentation as a part of response.
- welcome.jsp is responsible for rendering all UI stuff, fetches the attributes from request set by LoginServlet.java, displaying the fetched data.
If welcome.jsp was not there then LoginServlet.java has to perform other tasks also like fetching the data, preparing HTML response, setting this data in HTML. All UI stuff servlet has to do means by Java Developer but most likely UI developer are more efficient to do UI stuff. So in case of servlet either Java developer should learn UI technologies or always work closely with any UI developer.
On the other hand in case of JSP this task of Java and HTML can be separated. Let Java developer write LoginServlet.java. Let UI developer write welcome.jsp in HTML only. Later let Java Developer embed the JSP code in welcome.jsp
JSP Life cycle
JSP lifecycle methods
There are mainly three JSP lifecycle method:
- public void
_jspInit()
- public void
_jspService(HttpServletRequest req, HttpServletResponse res)
- public void
_jspDestroy()
JSP lifecycle steps
- Container translates the JSP to Servlet (welcome.jsp -> welcome_jsp.java)
- Container compile translated servlet (welcome_jsp.java -> welcome_jsp.class)
- Container loads servlet class
- Container invokes lifecycle method
_jspinti()
for initialization - Container invokes lifecycle method
_jspService()
- On further client request container directly invokes
_jspService()
- On container shut down, container invokes
_jspDestroy()
JSP Implicit Objects
JSP Scripting Elements
- JSP scripting elements are used to write Java statements in JSP
- There are mainly three types of JSP scripting elements
- Scriptlets
- Expressions
- Declarations
Scriptlets
- JSP scripting elements are used to write Java statements in JSP
- There are mainly three types of JSP scripting elements
- Scriptlets
- Expressions
- Declarations
Syntax
<%
...
%>
Example
<%
int i = 10;
out.println(i);
System.out.println(i);
...
%>
_jspService()
_jspService(){
...
int i = 10;
out.println(i);
System.out.println(i);
...
}
Expressions
- Expression tags are used to print/write the expression values
- Any expression will be put in
out.print(exp)
and then in_jspService()
- Semicolons are not allowed inside expression tags
Syntax
<%=
exp
%>
Example
<% String name = “Atul”; %>
<%= “Name” %>
<%= name %>
_jspService()
_jspService(){
...
String name = “Atul”;
out.print(“Name”);
out.print(name);
...
}
Declarations
- Methods definitions, blocks, constructors, class level variable are allowed inside declaration tags
- All code inside the declaration will be placed directly inside the translated servlet class and outside the
_jspService()
method
Syntax
<%!
//global var
//methods
}
%>
Example
<%!
String name = “Atul”;
void myMethod(){
...
}
%>
<h1>My Heading</h1>
welcom_jsp.java
public class welcome_jsp extends HttpServlet {
String name = “Atul”;
void myMethod(){
...
}
public void init(ServletConfig config) throws ServletException {}
public void destroy(){}
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PageContext pageContext = null;
HttpSession session = null
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = null;
...
out.write(“<h1>My Heading</h1>”);
...
int i = 10;
out.print(i);
System.out.println(i);
...
}
}
JSP Directives
Directive is a special instructions to container to perform the required task. There are mainly three type of directives
- include directive
- page directive
- taglib directive
1. include directive
- include directive is used to include one JSP or HTML in another JSP
- During JSP translation include directive line will be replaces with actual content
- One or more include directives are allowed inside JSP
- include directive can be placed at any position of the page
Syntax
<%@ include file=”filename1.jsp” %>
<%@ include file=”filename2.html” %>
2. page directive
page directive is used to perform page level operations eg. import, thread safe
Syntax
<%@ page
language=””
import=””
session=””
extends=””
isThreadSafe=””
errorPage=””
isErrorPage=””
isELIgnored=””
%>
language:
- language attribute is used to specify the language for the scriptlets and declarations
- Currently only java is the valid value which is also default value
- Value other than java will cause invalid attribute error
- Eg:
<%@ page language=”java” %>
import:
- import attribute is used to specify the packages to be imported for translated servlet
- one or more packages can be specified by comma separation
- Eg:
<%@ page import=”java.io.*,java.util.*””%>
session:
- Session object is used to enable and disable session attribute in JSP
- By default session object is enabled
- Eg:
<%@ page session=”false” %>
- If disables, session object cannot be used in JSP otherwise compilation error
extends:
- HttpJspBase is the default superclass for the translated servlet
- extends attributes can be used to replace this default HttpJspBase class by other
- If HttpServlet class is used as a superclass using extend attribute, you have to override any of the methods of HttpServlet class
- Eg:
<%@ page extends=”javax.servlet.http.HttpServlet” %>
<%@ page import=”java.io.IOException,javax.servlet.ServletException”%>
<%@ page extends=”javax.servlet.http.HttpServlet” %>
<html>
<body>
<h1>
<%!
public void service(HttpServletRequest req, HttpServletresponse) throws IOException, ServletException{
_jspService(req, res);
}
%>
</h1>
</body>
</html>
isThreadSafe:
- isThreaSafe attribute is used to specify the servlet Thread model required
- Default Servlet Thread Model is multi-thread model
- Default values of isThreadSafe attribute is true
- Eg:
<%@ page isThreadSafe=”false” %> //Servlet Single Thread Model
<%@ page isThreadSafe=”true” %> //Servlet Multi Thread Model
errorPage and isErrorPage:
- isErrorPage attribute used to specify the JSP page is error page (error.jsp)
- error.jsp will be displayed in case of any exception in other JSP files having errorPage=”error.jsp”
- In such a way error.jsp acts as centralized JSP for error handling
- Both attributes work in coordination with each other
index.jsp
<%@ page errorPage=”error.jsp” %>
<html>
<body>
<h1>
Welcome to Home
</h1>
<% int i = 10/0; %>
</body>
</html>
error.jsp
<%@ page isErrorPage=”true” %>
<html>
<body>
<h1>Error Occurred!</h1>
<%= exception %>
</body>
</html>
isELIgnored:
- isELIgnored attribute is used to enable or disable EL expressions
- From Tomcat 6.0, EL Expressions are enabled by defaults
index.jsp
<%@ page isELIgnored=”false” %>
<html>
<body>
<% request.setAttribute(“msg”, “My message”); %>
<h1>Messae: ${msg}</h1>
</body>
</html>
3. taglib directive
taglib directive is used to use the custom tags in JSP
JSP Standard Actions
<jsp:include>
<jsp:forward>
<jsp:param>
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:include>
- includes one JSP or HTMl inside another JSP
- includes response of included page at runtime
<jsp:include>
functionality is same as ofRequestDispatcher.include
method
Syntax
<jsp:include page=”JSP or HTML file with extension” />
<jsp:forward>
- used to forward the control from one JSP to another JSP or HTML
<jsp:forward>
functionality is same as ofRequestDispatcher.forward
method
Syntax
<jsp:forward page=”JSP or HTML file with extension” />
<jsp:param>
- used to send parameter data from one JSP to another while including or forwarding
- must be used along with
<jsp:include>
or<jsp:forward>
Syntax
<jsp:param name=”mobile” value=”9876543210” />
<jsp:useBean>
<jsp:useBean>
is used for creating Java Bean object
Syntax with example
<jsp:useBean id=”” class=”” scope=”” />
<jsp:useBean id=”user” class=”com.learnjsp.bean.User” scope=”session” />
- scope attribute used to tell the scope of the bean eg: request, session etc.
<jsp:setProperty>
<jsp:setProperty>
is used for storing data in Java Bean object
Syntax with example
<jsp:setProperty name=”” property=”” value=”” />
<jsp:setProperty name=”user” property=”userName” value=”Atul” />
<jsp:getProperty>
<jsp:getProperty>
is used to fetch data from Java Bean object
Syntax with example
<jsp:getProperty name=”” property=”” />
<jsp:getProperty name=”user” property=”userName” />
Include directive v/s Include action
Scopes
- Scope is used to specify the lifespan of an object
- Any data stored in object is persisted throughout the scope of object
- And this data can be accessed any time within the scope as per requirement
- Object that are bound to a particular scope called scoped object
- Data can be stored in scope as an attribute, attributes are name-value pair
- name of attribute is type of String
- value of attribute is type of Object
- These are read and write attributes
Methods for using scope object
void setAttribute(String attrName, Object attrValue)
Object getAttribute(String attrName)
void removeAttribute(String attrName)
Enumeration getAttributeNames()
Type of Servlet Scopes
There are mainly three types of servlet scopes
- Request scope
- Session scope
- Context scope
1. Request scope
- Data stored in
HttpServletRequest
will be available until request object destroyed - Scope of such data called request scope
- Request data can be accessed by single user within same request and before sending the response
2. Session scope
- Data stored in
HttpSession
object will be available until session persists - Scope of such data called session scope
- Session data can be accessed by single user across multiple requests
- User should belong to same session
3. Context scope
- Data stored in
ServletContext
will be available throughout the life of web application - Scope of such data is called context scope
- Context data can be accessed by multiple users across multiple requests
Type of JSP scopes
There are four types of JSP scopes
- Page scope
- Request scope
- Session scope
- Application scope
1. Page scope
- Data from page can be accessed within the same JSP only
- Data can be stored directly in request, session and application using
setAttribute
but - To save data in page scope you have to use implicit object
pageContext
- It is of
java.lang.Object
type - Methods of
PageContext
to manage attributes and its values
void setAttribute(String attrName, Object attrValue)
void setAttribute(String attrName, Object attrValue, int scope)
Object getAttribute(String attrName)
Object getAttribute(String attrName, int scope)
Object findAttribute(String attrName)
void removeAttribute(String attrName, int scope)
Enumeration getAttributeNamesInScope(int scope)
2. Request scope
- Data stored in
HttpServletRequest
will be available until request object destroyed - Scope of such data called request scope
- Request data can be accessed by single user within same request and before sending the response
3. Session scope
- Data stored in
HttpSession
object will be available until session persists - Scope of such data called session scope
- Session data can be accessed by single user across multiple requests
- User should belong to same session
4. Application scope
- Data stored in
ServletContext
will be available throughout the life of web application - Scope of such data is called context scope
- Context data can be accessed by multiple users across multiple requests