Uploaded by NOOBDADDY

ajava unit 1

advertisement
1
ADVANCED JAVA
PCC-CSE-306G
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced
2
Course Outcomes:
1. Knowledge of the structure and model of the Java programming
language, (knowledge)
2. 2. Use the Java programming language for various programming
technologies (understanding)
3. 3. Develop software in the Java programming language.
4. For basic concepts kindly visit
https://www.digimat.in/nptel/courses/video/106105191/L01.htm
l
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
3
UNIT-I
SERVLET
• Servlets are the Java programs that runs on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, then send response back to the
webserver.
Properties of Servlets :
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from web server.
Execution of Servlets :
Execution of Servlets involves six basic steps:
• The clients send the request to the web server.
• The web server receives the request.
• The web server passes the request to the corresponding servlet.
• The servlet processes the request and generates the response in the form of output.
• The servlet sends the response back to the web server.
• The web server sends the response back to the client and the client browser displays
it on the screen.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
4
UNIT-I
SERVLET
Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web
page.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
5
UNIT-I
SERVLET
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
SERVLET API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for
http requests only.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
SERVLET API
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
8
SERVLET INTERFACE
Servlet interface provides common behavior to all the servlets. Servlet
interface defines methods that all servlets must implement. It provides 3 life cycle
methods that are used to initialize the servlet, to service the requests, and to destroy
the servlet and 2 non-life cycle methods.
A generic servlet is a protocol independent Servlet that should always override the
service() method to handle the client request. The service() method accepts two
arguments ServletRequest object and ServletResponse object.
The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
9
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
• public void service(ServletRequest req,ServletResponse res) dispatches the request
to the protected service method by converting the request and response object into
http type.
• protected void service(HttpServletRequest req, HttpServletResponse res) receives
the request from the service method, and dispatches the request to the doXXX()
method depending on the incoming http request type.
• protected void doGet(HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
• protected void doPost(HttpServletRequest req, HttpServletResponse res) handles
the POST request. It is invoked by the web container.
• protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
1
0
LIFE CYCLE OF SERVLET
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
1
1
LIFE CYCLE OF SERVLET
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
1
2
LIFE CYCLE OF SERVLET
The web container maintains the life cycle of a servlet instance
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
1
3
LIFE CYCLE OF SERVLET
The web container maintains the life cycle of a servlet instance
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
• As displayed in the previous slide diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it
shifts to the end state.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
1
4
LIFE CYCLE OF SERVLET
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init() method
The init() Method
The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
1
5
LIFE CYCLE OF SERVLET
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException { // Initialization code... }
The service() Method
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException { }
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
1
6
LIFE CYCLE OF SERVLET
destroy method is invoked
The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
public void destroy()
ServletConfig is an object containing some initial parameters
or configuration information created by Servlet Container and passed to
the servlet during initialization. ServletConfig is for a particular servlet, that means one
should store servlet specific information in web.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
1
7
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
1
8
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
1
9
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
0
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
1
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
2
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
3
SERVLET WITH IDE
2. Create the servlet in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
4
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
5
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
6
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
7
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
8
SERVLET WITH IDE
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
2
9
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
0
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
1
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
2
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
3
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
4
SERVLET WITH IDE
3. add jar file in eclipse IDE:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
5
SERVLET WITH IDE
4. Start the server and deploy the project:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
6
SERVLET WITH IDE
4. Start the server and deploy the project:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
7
SERVLET WITH IDE
4. Start the server and deploy the project:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
8
SERVLET WITH IDE
4. Start the server and deploy the project:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
3
9
Servlet Collaboration
The exchange of information among servlets of a particular Java web application is
known as Servlet Collaboration. This enables passing/sharing information from
one servlet to the other through method invocations.
Ways of Servlet Collaboration
• Using RequestDispatcher include() and forward() method
• Using HTTPServletResponse sendRedirect() method
• Using ServletContext setAttribute() and getAttribute() methods
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
4
0
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the
following scopes:
• request scope
• session scope
• application scope
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
1
Attribute in Servlet
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
1.There are following 4 attribute specific methods. They are as
follows:public void setAttribute(String name,Object object):sets the
given object in the application scope.
2.public Object getAttribute(String name):Returns the attribute for
the specified name.
3.public Enumeration getInitParameterNames():Returns the names
of the context's initialization parameters as an Enumeration of String
objects.
4.public void removeAttribute(String name):Removes the attribute
with the given name from the servlet context.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G
4
2
CRUD in Servlet
A CRUD (Create, Read, Update and Delete) application is the most important application
for any project development. In Servlet, we can easily create CRUD application.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
3
CRUD in Servlet
Create "user905" table in Oracle Database with auto incrementing id using sequence.
There are 5 fields in it: id, name, password, email and country.
Programming to be done on compiler
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
4
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression,
encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove
the entry of filter from the web.xml file, filter will be removed automatically and we
don't need to change the servlet.
So maintenance cost will be less.
.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
5
Servlet Filter
Usage of Filter
recording all incoming requests
logs the IP addresses of the computers from which the requests originate
conversion
data compression
encryption and decryption
input validation etc.
Advantage of Filter
Filter is pluggable.
One filter don't have dependency onto another resource.
Less Maintenance
.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
6
Servlet Filter
Filter API
Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.
Filter
FilterChain
FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides
the life cycle methods for a filter.
.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
7
Servlet Filter
.
Method
Description
public void init(FilterConfig config)
init() method is invoked only once.
It is used to initialize the filter.
public
void doFilter() method is invoked every
doFilter(HttpServletRequest
time when user request to any
request,HttpServletResponse
resource, to which the filter is
response, FilterChain chain)
mapped.It is used to perform
filtering tasks.
public void destroy()
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
This is invoked only once when
filter is taken out of the service.
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
8
Servlet Filter
Simple Example of Filter
In this example, we are simply displaying information that filter is invoked automatically after the post processing of the request.
index.html
<a href="servlet1">click here</a>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
chain.doFilter(req, resp);//sends request to next resource
out.print("filter is invoked after");
}
public void destroy() {}
}
Faculty : Dr. Ashima Mehta
.
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
4
9
Servlet Filter
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
}
}
.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
0
Event and Listener in Servlet
Events are basically occurrence of something. Changing the state of an object is known
as an event.
We can perform some important tasks at the occurrence of these exceptions, such as
counting total and current logged-in users, creating tables of the database at time of
deploying the project, creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and
javax.servlet.http packages.
Event classes
The event classes are as follows:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
1
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
HttpSessionEvent
HttpSessionBindingEvent
Event interfaces
The event interfaces are as follows:
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
Faculty : Dr. Ashima Mehta
:
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
2
Pagination in Servlet
To divide large number of records into multiple parts, we use pagination. It allows user
to display a part of records only. Loading all records in a single page may take time, so it
is always recommended to created pagination. In servlet, we can develop pagination
example easily.
In this servlet pagination example, we are using MySQL database to fetch records.
Here, we have created "emp" table in "test" database. The emp table has three fields:
id, name and salary. Either create table and insert records manually or import our sql
file.
index.html
<a href="ViewServlet?page=1">View Employees</a>
:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
53
ViewServlet.java
package com.javatpoint.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String spageid=request.getParameter("page");
int pageid=Integer.parseInt(spageid);
int total=5;
if(pageid==1){}
else{
pageidpageid=pageid-1;
pageidpageid=pageid*total+1;
}
List<Emp> list=EmpDao.getRecords(pageid,total);
out.print("<h1>Page No: "+spageid+"</h1>");
out.print("<table border='1' cellpadding='4' width='60%'>");
out.print("<tr><th>Id</th><th>Name</th><th>Salary</th>");
for(Emp e:list){
out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getSalary()+"</td></tr>");
}
out.print("</table>");
Faculty : Dr. Ashima Mehta
out.print("<a href='ViewServlet?page=1'>1</a> ");
Branchout.print("<a
& Semester
: CSIT_VI SEM
href='ViewServlet?page=2'>2</a>
");
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
4
Annotation
In the Java computer programming language, an annotation is a form of syntactic
metadata that can be added to Java source code.
Like Javadoc tags, Java
annotations can be read from source files. Unlike Javadoc tags, Java annotations can
also be embedded in and read from Java class files generated by the Java compiler.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
5
SSI
All the servlets you've seen so far generate full HTML pages. If this were all that servlets
could do, it would still be plenty. Servlets, however, can also be embedded inside HTML
pages with something called server-side include (SSI)functionality. In many servers that
support servlets, a page can be preprocessed by the server to include output from
servlets at certain points inside the page. The tags used for a server-side include look
similar to those used for applets. Currently, the tag syntax varies across server
implementations. This section describes the syntax appropriate for the Java Web
Server. If you see this text, it means that the web server providing this page does not
support the SERVLET tag. docstore.mik.ua/orelly/java-ent/servlet/ch02_04.htm.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
6
LIFECYCLE OF JSP
A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet.
Paths Followed By JSP
The following are the paths followed by a JSP −
• Compilation
• Initialization
• Execution
• Cleanup
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
7
LIFECYCLE OF JSP
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
5
8
LIFECYCLE OF JSP
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The
four phases have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override
the jspInit() method −
public void jspInit(){ // Initialization code... }
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
5
9
LIFECYCLE OF JSP
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as
its parameters as follows −
void _jspService(HttpServletRequest request, HttpServletResponse response) { //
Service handling code... }
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.
The jspDestroy() method has the following form −
public void jspDestroy() { // Your cleanup code goes here. }
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
6
0
The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:
• JspPage
• HttpJspPage
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
6
1
JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are
processed by the JSP engine during translation of the JSP page. Any other text in the
JSP page is considered as HTML code or plain text.
Example:
<html>
<head>
<title>
My First JSP Page
</title>
</head>
<% int count = 0; %>
<body> Page Count is <% out.println(++count); %> </body> </html>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
2
Implicit Objects
These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
3
S.No.
Object & Description
Following table lists out the nine Implicit Objects that JSP supports −
1
request
This is the HttpServletRequest object associated with the request.
2
response
This is the HttpServletResponse object associated with the response to the client.
3
out
This is the PrintWriter object used to send output to the client.
4
session
This is the HttpSession object associated with the request.
5
6
7
8
9
Faculty : Dr. Ashima Mehta
Branch & Semester : CSIT_VI SEM
application
This is the ServletContext object associated with the application context.
config
This is the ServletConfig object associated with the page.
pageContext
This encapsulates use of server-specific features like higher performance JspWriters.
page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
The Exception object allows the exception data to be accessed by designated JSP.
Date:
Subject with Code : CLOUD COMPUTING(PCC-IT-
6
4
jsp directives
These are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
• page directive
• include directive
• taglib directive
• Syntax:<%@ directive attribute="value" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
5
jsp directives
JSP page directive
The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
6
jsp directives
1)import
The import attribute is used to import class,interface or all the members of a package.It
is similar to import keyword in java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
7
jsp directives
2)contentType
The contentType attribute defines the MIME(Multipurpose
Internet Mail Extension) type of the HTTP response
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
8
jsp directives
3)extends
The extends attribute defines the parent class that will be
inherited by the generated servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet
interface.
Example of info attribute
<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
6
9
jsp directives
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle
output generated by the JSP page.The default size of the buffer is
8Kb.
Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
0
jsp directives
6)language
The language attribute specifies the scripting language used in
the JSP page. The default value is
"java".
8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this
behaviour of JSP page, you can use isThreadSafe attribute of page
directive.The value of isThreadSafe value is true.If you make it
false, the web container will serialize the multiple requests, i.e. it
will wait until the JSP finishes responding to a request before
passing another request to it.If you make the value of
isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
1
jsp directives
9)errorPage
The errorPage attribute is used to define the error page, if
exception occurs in the current page, it will be redirected to the
error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
Faculty : Dr. Ashima Mehta
</body>
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
2
jsp include directive
The include directive is used to include the contents of any
resource it may be jsp file, html file or text file. The include
directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it
will be better to include static resource).
The include directive is used to include the contents of any
resource it may be jsp file, html file or text file. The include
directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it
will be better to include static resource).
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
3
JSP Taglib directive
The JSP taglib directive is used to define a tag library that defines
many tags. We use the TLD (Tag Library Descriptor) file to define
the tags. In the custom tag section we will use this tag so it will be
better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %
>
Example of JSP Taglib directive
In this example, we are using our tag named currentDate. To use
this tag we must specify the taglib directive so the container may
get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
Faculty : Dr. Ashima Mehta
</body>
</html> &
Branch
Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
4
EXCEPTION
Exception Handling in JSP
The exception is normally an object that is thrown at runtime.
Exception Handling is the process to handle the runtime errors.
There may occur exception any time in your web application. So
handling exceptions is a safer side for the web developer. In JSP,
there are two ways to perform exception handling:
By errorPage and isErrorPage attributes of page directive
By <error-page> element in web.xml file
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
5
EXCEPTIONExample of exception handling in jsp by the elements
of page directive
In this case, you must define and create a page to handle the
exceptions, as in the error.jsp page. The pages where may occur
exception, define the errorPage attribute of page directive, as in
the process.jsp page.
There are 3 files:
index.jsp for input values
process.jsp for dividing the two numbers and displaying the result
error.jsp for handling the exception
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
6
EXCEPTION
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
7
EXCEPTION
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
8
EXCEPTION
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
7
9
EXCEPTION
Output of this example:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
0
EXCEPTION
Output of this example:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
1
EXCEPTION
Output of this example:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
2
EXCEPTION
Output of this example:
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
3
JSP Action Tags
action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The
Jsp action tags are given below.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
4
JSP Action Tags
JSP Action Tags
Description
jsp:forward
forwards the request and response
to another resource.
jsp:include
includes another resource.
jsp:useBean
creates or locates bean object.
jsp:setProperty
sets the value of property in bean
object.
jsp:getProperty
prints the value of property of the
bean.
jsp:plugin
embeds another components such
as applet.
jsp:param
sets the parameter value. It is used
in forward and include mostly.
jsp:fallback
can be used to print the message if
plugin is working. It is used in
jsp:plugin.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
5
JSP specification provides Standard(Action) tags for use within your JSP pages.
These tags are used to remove or eliminate scriptlet code from your JSP page because
scriplet code are technically not recommended nowadays.
It's considered to be bad practice to put java code directly inside your JSP page.
Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which
are used to perform some specific task.
The following are some JSP Standard Action Tags available:
Action Tag
Description
jsp:forward
forward the request to a
new page
Usage : <jsp:forward
page="Relative URL" />
jsp:useBean
instantiates a JavaBean
Usage : <jsp:useBean
id="beanId" />
jsp:getProperty
retrieves a property from a
JavaBean instance.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
6
MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
Navigation Control is centralized
Easy to maintain the large application
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
7
MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
Navigation Control is centralized
Easy to maintain the large application
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
8
MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
Navigation Control is centralized
Easy to maintain the large application
For programming example write servlet collaboration program
that involves forward and include method
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
8
9
JSTL
JSTL (JSP Standard Tag Library)
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development.
Advantage of JSTL
Fast Development JSTL provides many tags that simplify the JSP.
Code Reusability We can use the JSTL tags on various pages.
No need to use scriptlet tag It avoids the use of scriptlet tag.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
0
JSTL
JSTL Formatting tags
The formatting tags provide support for message formatting, number and date formatting
etc. The url for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
The JSTL formatting tags are used for internationalized web sites to display and format
text, the time, the date and numbers. The syntax used for including JSTL formatting
library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
1
JSTL
JSTL Formatting tags
The formatting tags provide support for message formatting, number and date formatting
etc. The url for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
The JSTL formatting tags are used for internationalized web sites to display and format
text, the time, the date and numbers. The syntax used for including JSTL formatting
library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
2
JSTL
Formatting Tags
Descriptions
fmt:parseNumber
It is used to Parses the string representation of a currency,
percentage or number.
fmt:timeZone
It specifies a parsing action nested in its body or the time zone for any
time formatting.
fmt:formatNumber
It is used to format the numerical value with specific format or
precision.
fmt:parseDate
It parses the string representation of a time and date.
fmt:bundle
It is used for creating the ResourceBundle objects which will be used
by their tag body.
fmt:setTimeZone
It stores the time zone inside a time zone configuration variable.
fmt:setBundle
It loads the resource bundle and stores it in a bundle configuration
variable or the named scoped variable.
fmt:message
It display an internationalized message.
fmt:formatDate
It formats the time and/or date using the supplied pattern and styles.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
3
JSTL XML tags
The JSTL XML tags are used for providing a JSP-centric way of manipulating and
creating XML documents.
The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has custom
tags used for interacting with XML data. The syntax used for including JSTL XML tags
library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
4
XML Tags
Descriptions
x:out
Similar to <%= ... > tag, but for XPath expressions.
x:parse
It is used for parse the XML data specified either in the tag body or an
attribute.
x:set
It is used to sets a variable to the value of an XPath expression.
x:choose
It is a conditional tag that establish a context for mutually exclusive
conditional operations.
x:when
It is a subtag of that will include its body if the condition evaluated be
'true'.
x:otherwise
It is subtag of that follows tags and runs only if all the prior conditions
evaluated be 'false'.
x:if
It is used for evaluating the test XPath expression and if it is true, it will
processes its body content.
x:transform
It is used in a XML document for providing the XSL(Extensible
Stylesheet Language) transformation.
x:param
It is used along with the transform tag for setting the parameter in the
XSLT style sheet.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
5
JSTL SQL Tags
The JSTL sql tags provide SQL support. The url for the sql tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
The SQL tag library allows the tag to interact with RDBMSs (Relational Databases)
such as Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL
SQL tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
9
6
SQL Tags
sql:setDataSource
Descriptions
JSTL SQL Tags
Listfor creating a simple data source suitable only for prototyping.
It is used
sql:query
It is used for executing the SQL query defined in its sql attribute or the body.
sql:update
It is used for executing the SQL update defined in its sql attribute or in the
tag body.
sql:param
It is used for sets the parameter in an SQL statement to the specified value.
sql:dateParam
It is used for sets the parameter in an SQL statement to a specified
java.util.Date value.
sql:transaction
It is used to provide the nested database action with a common connection.
Faculty : Dr. Ashima Mehta
Branch & Semester : CSE_CSIT_VI SEM
Date:
Subject with Code :Advanced Java(PCC-CSE-306G)
For more understanding kindly visit the
following url for advanced java concepts
https://www.youtube.com/watch?v=Aer8hsbPUo
97
Download