Documente Academic
Documente Profesional
Documente Cultură
Servlet
1/16/17
CONTENTS
CGI
1/16/17
Need
CGI
vs Servlet
What is Servlet
Servlet Life Cycle
1/16/17
Universal
Automatic updates
Content
1/16/17
1/16/17
1/16/17
1/16/17
1/16/17
1/16/17
10
1/16/17
11
1/16/17
12
CGI Scripts
CGI
client
client
server
script
1/16/17
14
1/16/17
15
1/16/17
16
Servlet
servlet is a server side platform independent,
dynamic and multithread java program, which
runs in the context of server for extending the
functionality of server. When multiple users
make a request to the same servlet then all
requests will be processed by the container by
creating multiple threads for the same servlet. In
order to deal with these servlet programming, we
must import
1/16/17
17
javax.servlet.*;
javax.servlet.http.*; into our java program.
javax.servlet.Servletis one of pre-defined top mostinterface,
which is containinglife cyclemethods[init(),service(),destroy()
javax.servlet.GenericServletis one of the predefined abstract class
which is implementingjavax.servlet.Servletinterface, this
GenericServlet class is used for developing protocol independent
applications [ But in real time we will use protocol dependent
applications only, so GenericServlet wont be appeared in real time
]
Javax.servlet.http.HttpServletis sub class of GenericServlet used
for developing protocol dependent application [HTTPprotocol ]
1/16/17
18
What is a Servlet?
Servlet
1/16/17
19
1/16/17
20
1/16/17
21
Servlets
client
client
server
servlet
1/16/17
Running
Disadvantage:
Less
23
1/16/17
Advantage
better performance: because it creates a thread for each
request not process.
Portability: because it uses java language.
Robust: Servlets are managed by JVM so no need to worry
about memory leak, garbage collection etc.
Secure: because it uses java language..
24
Server
It
Web Server
Web server contains only web or servlet container. It can be used for
servlet, jsp, struts, jsf etc. It can't be used for EJB(Enterprise java beans).
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for
servlet, jsp, struts, jsf, ejb etc.
Application Server/ EJB container provides most of the system
level services like transaction handling, logging, load balancing,
persistence mechanism, exception handling and so on. Developer
has to focus only on business logic of the application.
EJB container manages life cycle of ejb instances thus developer
needs not to worry about when to create/delete ejb objects.
Example of Application Servers are:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by Oracle.
1/16/17
Web Server
Application
25
26
Container
It
It
1/16/17
27
28
First
29
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
1/16/17
31
1/16/17
32
1/16/17
33
1/16/17
After
Generic Servlet:
GenericServlet class is direct subclass of Servlet interface.
Generic Servlet is protocol independent.It handles all types of protocol
like http, smtp, ftp etc.
Generic Servlet only supports service() method.It handles only simple
request
public void service(ServletRequest req,ServletResponse res ).
HttpServlet:
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is protocol dependent. It handles only http protocol.
HttpServlet supportspublic void service(ServletRequest
req,ServletResponse res ) andprotected void
service(HttpServletRequest req,HttpServletResponse res).
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions(
)etc.
35
1/16/17
36
1/16/17
37
1/16/17
38
1/16/17
GET
Content Type
1/16/17
40
There
1. By
2. By
1/16/17
The
The
41
Thedirectory
The
42
43
1/16/17
The
In
44
1/16/17
publicclassDemoServletextendsHttpServlet
{
publicvoiddoGet (HttpServletRequestreq, HttpServletResponseres)
throwsServletException, IOException
{
res.setContentType("text/html"); //settingthecontenttype
PrintWriterpw=res.getWriter(); //getthestreamtowritethedata
//writinghtmlinthestream
pw.println("<html><body>");
pw.println("Welcometoservlet");
pw.println("</body></html>");
pw.close(); //closingthestream
}
}
45
For
Server
servlet-api.jar
Apache Tomacat
weblogic.jar
Weblogic
javaee.jar
Glassfish
javaee.jar
JBoss
Ways
1/16/17
Put the java file in any folder. After compiling the java file, paste the
class file of servlet inWEB-INF/classes directory.
46
The web container uses the Parser to get the information from
the web.xml file. There are many xml parsers such as SAX,
DOM and Pull.
1/16/17
47
<web-app>
<servlet>
<servlet-name>TestExample</servlet-name>
<servlet-class>DemoServlet</servlet-class>
1/16/17
<init-param>
<param-name>myName</param-name>
<param-value>myValue</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>TestExample</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
48
<<
ws
s
ee
rb r
T
- v
v
hl
la
e
pe
rttp tec
>
n
m
al
r a
m
p
e
ps
ti> s
o>
n
o
g
m
>
a
n
y
el
e
m
e
n
ts
49
50
Ports
A
A service is associated
Typical port numbers:
notion, so
HttpServlet class
HttpServlet class extends the GenericServlet class and
implements Serializable interface.
It
1/16/17
The
52
Session tracking
HTTP
1/16/17
Session
53
1/16/17
Cookies
Cookies
1/16/17
55
Cookies
cookies are text files stored on the client computer by web
server and they are kept for various information tracking purpose
(called session tracking)
Java Servlet trasperantly support HTTP Cookies.
Cookies Contains following parameters:
Name
Value
Expiration Date
Path the Cookie is valid for
Domain the Cookie is Valid for
Need for a secure connection to exists to use the coookie.
1/16/17
56
Creating Cookies
firstName = new Cookie("name",
jamesbond);
Cookies are sent using HTTP header.
To send this cookie to clients browser, servlet
must add it to response object using addCookie()
method before sending any content.
Response
1/16/17
Cookie
.addCookie(firstName);
57
Retrieving Cookies
method of HttpServletRequest
returns an array of Cookie Object.
Cookie[] getCookies()
1/16/17
getCookies()
58
Cookie methods
1/16/17
59
Cookie methods
1/16/17
60
URL-Rewriting
Idea
Advantage
Works
Disadvantages
61
1/16/17
Client
Advantage
Works
Disadvantages
Lots of tedious processing as Extra form
submission is required on each pages.
Only textual information can be used.
All
62
1/16/17
Generate
HTTP Session
1/16/17
63
64
Cookies vs session
Cookie
1/16/17
Session
65
ServletConfig
1/16/17
66
1/16/17
public
67
ServletContext
This
web.xml
It
1/16/17
is an interface.
It is used to communicate with ServletContainer.
Due to this there is only one servletContext for
the whole project/application.
It is used to
from
is used to
68
ServletContext methods
String
1/16/17
getInitParameter(Stringname)
Enumeration getInitParameterNames()
Object getAttribute(Stringname)
Enumeration getAttributeNames()
void setAttribute(Stringname, Objectobject)
void removeAttribute(Stringname)
String getRealPath(Stringpath)<input
type="hidden" name="sessionID"
value="..."><input type="hidden"
name="sessionID" value="...">
RequestDispatcher getRequestDispatcher(String
path)
69
ServletConfig
1.ServletContext available in
javax.servlet.*; package
2.ServletContext object is global to
entire web application
3.Object of ServletContext will be
created at the time of web
application deployment
4.Scope: As long as web application
is executing, ServletContext object
will be available, and
5. it will be destroyed once the
application is removed from the
server.
6.ServletContext object will be
available even before giving the first
request
1/16/17
1.ServletConfig available in
javax.servlet.*; package
2.ServletConfig object is one per
servlet class
3. Object of ServletConfig will be
created during initialization process
of the servlet
4. destroyed once the servlet
execution is completed.
5.This Config object is public to a
particular servlet only
ServletContext
70
Servlet Filter
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.
Theservlet 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.
1/16/17
Afilteris
71
Servlet Filters
1/16/17
Uses of Filters
l Authentication - Blocking requests based on user identity.
Logging and auditing - Tracking users of a web application.
Image conversion - Scaling maps, and so on.
Data compression - Making downloads smaller.
Localization - Targeting the request and response to a
particular locale.
Encryption
Debugging
72
Filter API
1/16/17
73
Filter Interface
Desription
public void
doFilter(HttpServletRequest
request,HttpServletResponse
response, FilterChain chain)
1/16/17
Method
74
1/16/17
75
Filter Config
is used by a servlet container to pass
information to a filter during initailization.
4 methods:
1) String getFilterName()
2) String getInitParameter()
3) Enumeration getInitParameterNames()
4) ServletContext getServletContext()
1/16/17
It
76
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> servlet1 </servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name> MyFilter </filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
77
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.*;
publicclassMyFilterimplementsFilter{
publicvoidinit(FilterConfigarg0)throwsServletException{}
publicvoiddoFilter(ServletRequestreq,ServletResponseresp,
FilterChainchain)throwsIOException,ServletException{
PrintWriterout=resp.getWriter();
out.print("filterisinvokedbefore");
chain.doFilter(req,resp);//sendsrequesttonextresource
out.print("filterisinvokedafter");
}
publicvoiddestroy(){}
}
78
Servlet code
1/16/17
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;
publicclassHelloServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
out.print("<br>welcometoservlet<br>");
79
Servlet Events
An event refers to a set of actions that may occur while an
application is running.
It could also be defined as a set of actions, such as clicking a button
or pressing a key, performed by a user.
The following list shows some of the events that may occur during
the life cycle of a servlet:
Initializing servlets.
Adding, removing or replacing attributes in ServletContext.
Creating, activating Session.
Adding, removing, or replacing attributes in a servlet session.
Destroying servlets
1/16/17
80
information to a servlet.
There are two event listeners
1. ServletRequestListner
2. ServletRequestAttributeListner
Servlet Session level events: Refers to the events that are used to
maintain the session of a client.
There are three event listeners
1. HttpSessionListner
2. HttpSessionAttributeListner
3. HttpSessionActivationListner
82
Event classes
ServletRequestEvent
ServletRequestAttributeEvent
ServletContextEvent
ServletContextAttributeEvent
HttpSessionEvent
HttpSessionBindingEvent
Event interfaces
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
1) Void
requestIniatialized(ServletRequestEvent e)
It is invoked when request is about to come into
scope of the web application.
2) Void requestDestroyed(ServletRequestEvent e)
It is invoked when request is about to go out of
scope of the web application.
1/16/17
Methods
85
ServletContextEvent and
ServletContextListener
If
Method
of ServletContextEvent class
There is only one method defined in the
ServletContextEvent class:
public ServletContext getServletContext():
returns the instance of ServletContext.
Methods of ServletContextListener interface
There are two methods declared in the
ServletContextListener interface which must be
implemented by the servlet programmer to
perform some action such as creating database
connection etc.
public void
contextInitialized(ServletContextEvent e): is
1/16/17
88
HttpSessionEvent and
HttpSessionListener
The
Methods of HttpSessionListener
interface
There are two methods declared in the
HttpSessionListener interface which must be
implemented by the servlet programmer to perform
some action
.public
void
sessionCreated(HttpSessionEvent
e):
is
invoked when session object is created.
public
void
sessionDestroyed(ServletContextEvent e): is
invoked when session is invalidated.
1/16/17
Tomcat is both a web server and a web container, but it's not really
meant to function as a high performance web server, nor does it
include some features typical of a web server. Tomcat is meant to
be used in conjunction with the Apache web server, where Apache
manages static pages, caching, redirection, etc. and Tomcat
handles the container (web application) functions. You'll often hear
the phrase "Apache Tomcat" together, which is both a proper
attribution of the Tomcat project (as part of the Apache Foundation),
but also appropriate as a label, as they're usually used together as
a package.
91
Read
Servlets Tasks
1/16/17
93
Apache
Apache
1/16/17
servers)
94
Tomcat
Tomcat
Apache
Apache
Tomcat
Its
1/16/17
Apache
free)
95