Advanced Java Servlet Overview
Advanced Java Servlet Overview
ADVANCED JAVA
PCC-CSE-306G
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
[Link]
l
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 Date:
Branch & Semester : CSIT_VI SEM 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.
UNIT-I
SERVLET
SERVLET API
The [Link] and [Link] packages represent interfaces and classes for
servlet api.
The [Link] package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The [Link] package contains interfaces and classes that are responsible for
http requests only.
SERVLET API
Interfaces in [Link] package
There are many interfaces in [Link] package. They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM 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.
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.
Servlet Collaboration
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
Attribute in Servlet
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.
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
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 [Link] file, if we remove
the entry of filter from the [Link] file, filter will be removed automatically and we
don't need to change the servlet.
So maintenance cost will be less.
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
Servlet Filter
Filter API
Like servlet filter have its own API. The [Link] 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.
Servlet Filter
Method Description
. public void init(FilterConfig init() method is invoked only
config) once. It is used to initialize the
filter.
public void doFilter() method is invoked
doFilter(HttpServletRequest every time when user request
request,HttpServletResponse to any resource, to which the
response, FilterChain chain) filter is [Link] is used to
perform filtering tasks.
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.
[Link]
<a href="servlet1">click here</a>
[Link]
import [Link];
import [Link];
import [Link].*;
PrintWriter out=[Link]();
[Link]("filter is invoked before");
Servlet Filter
[Link]
import [Link];
import [Link];
import [Link];
import [Link].*;
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<br>welcome to servlet<br>");
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 Date:
:
Branch & Semester : CSIT_VI SEM 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.
[Link]
<a href="ViewServlet?page=1">View Employees</a>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out=[Link]();
String spageid=[Link]("page");
int pageid=[Link](spageid);
int total=5;
if(pageid==1){}
else{
pageidpageid=pageid-1;
pageidpageid=pageid*total+1;
}
List<Emp> list=[Link](pageid,total);
Annotation
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. [Link]/orelly/java-ent/servlet/ch02_04.htm.
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
LIFECYCLE OF JSP
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
−
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. }
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 <% [Link](++count); %> </body> </html>
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.
response
2 This is the HttpServletResponse object associated with the response to the client.
out
3 This is the PrintWriter object used to send output to the client.
session
4 This is the HttpSession object associated with the request.
application
5 This is the ServletContext object associated with the application context.
config
6 This is the ServletConfig object associated with the page.
pageContext
7 This encapsulates use of server-specific features like higher performance JspWriters.
page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9 The Exception object allows the exception data to be accessed by designated JSP.
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" %>
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 Date:
Branch & Semester : CSE_CSIT_VI SEM 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 [Link]
is similar to import keyword in java class or interface.
Example of import attribute
<html>
<body>
</body>
</html>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM 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>
</body>
</html>
jsp directives
3)extends
The extends attribute defines the parent class that will be
inherited by the generated [Link] 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>
</body>
</html>
jsp directives
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle
output generated by the JSP [Link] default size of the buffer is
8Kb.
Example of buffer attribute
<html>
<body>
</body>
</html>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM 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 [Link] you want to control this
behaviour of JSP page, you can use isThreadSafe attribute of page
[Link] value of isThreadSafe value is [Link] 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 [Link] you make the value of
isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM 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.
<mytag:currentDate/>
</body>
</html>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM 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 [Link] file
EXCEPTION
[Link]
<form action="[Link]">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
EXCEPTION
[Link]
<%@ page errorPage="[Link]" %>
<%
String num1=[Link]("n1");
String num2=[Link]("n2");
int a=[Link](num1);
int b=[Link](num2);
int c=a/b;
[Link]("division of numbers is: "+c);
%>
[Link]
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM Subject with Code :Advanced Java(PCC-CSE-306G)
7
8
EXCEPTION
[Link]
<%@ page errorPage="[Link]" %>
<%
String num1=[Link]("n1");
String num2=[Link]("n2");
int a=[Link](num1);
int b=[Link](num2);
int c=a/b;
[Link]("division of numbers is: "+c);
%>
[Link]
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSE_CSIT_VI SEM Subject with Code :Advanced Java(PCC-CSE-306G)
7
9
EXCEPTION
Output of this example:
EXCEPTION
Output of this example:
EXCEPTION
Output of this example:
EXCEPTION
Output of this example:
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:
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
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
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
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.
JSTL
JSTL Formatting tags
The formatting tags provide support for message formatting, number and date formatting
etc. The url for the formatting tags is [Link] 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="[Link] prefix="fmt" %>
JSTL
JSTL Formatting tags
The formatting tags provide support for message formatting, number and date formatting
etc. The url for the formatting tags is [Link] 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="[Link] prefix="fmt" %>
JSTL
fmt:formatDate It formats the time and/or date using the supplied pattern
and styles.
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:otherwise It is subtag of that follows tags and runs only if all the prior
conditions evaluated be 'false'.
x:param It is used along with the transform tag for setting the
parameter in the XSLT style sheet.
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.
97