Download - Begin Servlet
-
8/22/2019 Begin Servlet
1/52
Servlet: Introduction
-
8/22/2019 Begin Servlet
2/52
New methods added in HTTPServlet10
HTTPServlet9
GenericServlet8Servlet Class hierarchy7
Servlet instance6
Servlet Life Cycle5
Servlet interface4
JSDK3
Servlet Request Response Mechanism2
Definition1
Contents
-
8/22/2019 Begin Servlet
3/52
Deploying20
Packaging19
Writing web.xml18
web.xml17
Brief introduction to XML16
Deployment Descriptors15
HTML file with a link to servlet14
Steps to deploy a web application13
A Simple Servlet12
Request and Response object11
Contents
-
8/22/2019 Begin Servlet
4/52
Getting single parameters30
HttpServletResponse Interface29
ServletResponse Interface28
HttpServletRequest Interface27
ServletRequest26
Request and Response hierarchy25
Execution24Deployment23
Steps for packaging22
Packaging and deploying the servlet21
Contents
-
8/22/2019 Begin Servlet
5/52
SingleThreadModel Interface34
Servlet variable initialization33Servlet to get multiple param32
Getting multiple parameters31
Contents
-
8/22/2019 Begin Servlet
6/52
Know
What a servlet is and its lifecycle
The Request Response Mechanism
Servlet classes
HttpServletRequest and HttpServletResponse
classes
-
8/22/2019 Begin Servlet
7/52
Be Able To
Write a simple servlet
-
8/22/2019 Begin Servlet
8/52
Definition
A servlet is a server side program writtenin Java that resides and executes in an
application server
It enables the delivery ofdynamic content
-
8/22/2019 Begin Servlet
9/52
Servlet Request Response Mechanism
Servlet
Database
Client Web Server
Application ServerRequest
Response
If request is for static pagereturn the page as response
ElsePass the request to application server
-
8/22/2019 Begin Servlet
10/52
JSDK
Java Servlet Development Kit (JSDK)contains the class library that is requiredto create servlets and JSP.
The 2 packages that are required to createservlets are javax.servlet andjavax.servlet.http.
A java class is a servlet if it directly orindirectly implements the Servletinterface.
-
8/22/2019 Begin Servlet
11/52
Servlet interface
public void init(ServletConfigconfig) throws ServletException
public void service(ServletRequestreq, ServletResponse res) throwsServletException,java.io.IOException
public void destroy()
public ServletConfiggetServletConfig()
public String getServletInfo()
Life cycle methods
-
8/22/2019 Begin Servlet
12/52
Servlet instanceServletInstantiation
New instancecreated on firstrequest
Initialized Servlet init() is called
Application Server
Request servicingServlet
service() is called
DestroyedServlet
destroy() is called
Initialization
Begin service
Destruction
Servlet Life Cycle
First request
Subsequent requests
-
8/22/2019 Begin Servlet
13/52
Servlet instance
Only one instance of a particular servlet
class is created. The same instance is
used for all the requests.
When the container shuts down, this
instance is destroyed.
-
8/22/2019 Begin Servlet
14/52
Servlet instance
The container runs multiple threads on the
service() method to process multiple
requests.
Only a single instance of servlet of each
type ensures minimum number of servlet
objects created and destroyed on the
server adds to scalability
-
8/22/2019 Begin Servlet
15/52
Servlet Class hierarchy
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
javax.servlet.Servlet
-
8/22/2019 Begin Servlet
16/52
GenericServlet GenericServlet class provides basic
implementation of the Servlet interface.
This is an abstract class. It implements all the
methods except service() method.
-
8/22/2019 Begin Servlet
17/52
GenericServlet Other methods included are:
public void log(String message)
public void init() throwsServletException
The implementation ofinit(ServletConfig config)callsinit()method.
-
8/22/2019 Begin Servlet
18/52
HTTPServlet
HTTPServlet inherits from theGenericServlet and provides a HTTP
specific implementation of the Servlet
interface.
The service(ServletRequest req,
ServletResponse res) method is
implemented.
-
8/22/2019 Begin Servlet
19/52
HTTPServlet
Since this implementation specific toHTTP protocol, there are methods thatspecific to each HTTP methods like GET,
POST, TRACE etc. It is an abstract class and is subclassed to
create an HTTP servlet suitable for a Website.
-
8/22/2019 Begin Servlet
20/52
New methods added in HTTPServlet
protected voidservice(HttpServletRequest req,HttpServletResponse res) throwsServletException, java.io.IOException
protected void doXXX(HttpServletRequestreq, HttpServletResponse res)
XXX is GET, POST, TRACE, PUT, DELETE
A subclass of HttpServlet must override
at least one method, usually one ofdoGet,doPost, doDelete, doPut, doHead
init and destroy to manage resources thatare held for the life of the servlet.
Our focus
-
8/22/2019 Begin Servlet
21/52
Request and Response object
Servlet A
Request forservlet A
Response
Client
Web Server
Application server
HTTP
requestpacket
HttpServletRequest Object
HttpServletResponse Object
Web Container
HTTPresponse
packet
-
8/22/2019 Begin Servlet
22/52
A Simple Servlet
import javax.servlet.http.*;import javax.servlet.*;import java.io.*;
publicclass GreetingServlet extendsHttpServlet{String welcomeMsg
=Welcome to simple servlet;java.util.Date currDate;
greet.war
-
8/22/2019 Begin Servlet
23/52
public void doGet(HttpServletRequestrequest,HttpServletResponse response)throws ServletException, IOException{
currDate=new java.util.Date();PrintWriter out = response.getWriter();response.setContentType("text/html");
out.println("Greetings Servlet );
out.println("+
welcomeMsg+
+currDate+");}} -
8/22/2019 Begin Servlet
24/52
Steps to deploy a web application
Write servlets. Compile them.
Write html and jsp files.
Write deployment descriptor web.xml. Package the application
Deploy the application
-
8/22/2019 Begin Servlet
25/52
HTML file with a link to servlet
Greet
Simple ExampleClick to invoke the servletGreetings
index.html
We will map the servlet and the url shortly
-
8/22/2019 Begin Servlet
26/52
Deployment Descriptor
Deployment descriptors is an xml file that helps inmanaging the configuration of an application.
This is the file using which an application can
communicate with the container and vice versa.
For a web application, the deployment descriptor file
name is web.xml.
The Java Servlet specifies a document type
definition for deployment descriptor which isavailable at
http://java.sun.com/j2ee/dtds/web_app_2_2.dtd
-
8/22/2019 Begin Servlet
27/52
Brief introduction to XML
XML stands for EXtensible Markup Language.XML is a markup language much like HTML.
XML was designed to describe data. XML was
created to structure, store and to send
information.
XML is a cross-platform, software and hardware
independent tool for transmitting information.
XML tags are not predefined. You must defineyour own tags.
One of the uses of XML is to exchange data.
-
8/22/2019 Begin Servlet
28/52
web.xml Servlet components that are used in web
application along with their fully qualified class
names
URLs for servlets
Welcome file name
Initialization parameters if any
Session Configuration
Application Lifecycle Listener classes
Filter Definitions and Filter Mappings Error Pages
Environment Variable Mappings
Mime type mapping
Our focus in this chapter
-
8/22/2019 Begin Servlet
29/52
Writing web.xml
Greet
Greet
simple
GreetingServlet
Optional. IDEs use it for listing webapplication name
entifier for this servlet in the web appliaction
Fully qualified name for the servlet
-
8/22/2019 Begin Servlet
30/52
Greet
/greet.do
Append a / for tomcat
URL that is going to used to access thiscomponent
specify the identifier for whichcomponent url is going to be mapped
index.htmldefault.jsp
Optional because index.html is welcome file by defaul
index.html is not found, container will look for default.jsp.
-
8/22/2019 Begin Servlet
31/52
Packaging
Packaging application means placing thefiles in the appropriate placeholders
(directory).
-
8/22/2019 Begin Servlet
32/52
Packaging
Servlet specification lays out the rules of how
enterprise applications should be packaged.
This is necessary so that the container (any j2ee
container) knows where to find the files (theservlet class files, html class files etc.)
Since a web application is composed of many
files, the specification also tells us how to
archive the files and deploy it as single file
application.
-
8/22/2019 Begin Servlet
33/52
Deploying
Deploying means uploading theapplication on the server.
If there is any problem with the packaging,
the application will not be uploaded. There are many J2EE IDEs that help in
developing and packaging the application.
-
8/22/2019 Begin Servlet
34/52
Deploying
Most of the application servers support hotdeployment.
Most of the application servers support
start and stop of applications that aredeployed.
-
8/22/2019 Begin Servlet
35/52
Packaging and deploying the servlet
Web Application 1
Servlets
JSPs/HTML
JavaClasses
DeploymentDescriptor
(web.xml)
Web Application 2
Servlets
JSPs/HTML
Java
Classes
DeploymentDescriptor
(web.xml)
Components forming the web application.
xxx.war
-
8/22/2019 Begin Servlet
36/52
Steps for packaging
Create a folder.
Let us name the folder as slide1ex1.
Place htmls and jsps in folder
Place the index.html inside slide1ex1
Create a folder called WEB-INF.Created! Note the case is important here.
Place web.xml inside the folder
Placed!
Create a folder called classes inside WEB-INFand all the java classes created inside it.
Created and placed GreetingServlet.class.
-
8/22/2019 Begin Servlet
37/52
Deployment
As per j2ee specification, a jar file should becreated with the extension .war. This war filehas to be then deployed depending on theapplication server.
Jar Command to create war
path/simple:> jar cvf simple.war*.*
For tomcat, just copy the simple folder into thefolder called webapps.
-
8/22/2019 Begin Servlet
38/52
Deployment
Start the tomcat server. Type in the following url in the address bar http://localhost:8080/slide1ex1
/index.html Or simply
http://localhost:8080/slide1ex1
Server nameDefault protocol where tomcat ruprotocolFoldername
-
8/22/2019 Begin Servlet
39/52
According to j2eespecs, war file has to
be created. Fortomcat we dont doso. So, does this
mean that tomcatdoes not strictly
follow j2ee specs?
Tomcat followsj2ee specs! It just
gives you a simpleway to deploy yourapplication.
Another option todeploy would be toplace the war file
-
8/22/2019 Begin Servlet
40/52
Request and Response hierarchy
HttpServletResponse
ServletResponse
HttpServletRequest
ServletRequest
-
8/22/2019 Begin Servlet
41/52
ServletRequest
BufferedReader getReader()
ServletInputStream
getInputStream() int getContentLength()
Enumeration getParameterNames()
String getParameter(String name) String[] getParameterValues(Stringname)
Example ahead
Allows you to read raw bytes
or characters from the strea
-
8/22/2019 Begin Servlet
42/52
HttpServletRequestInterface
String getMethod()
String getHeader(String name)
Enumeration getHeaderNames() String getQueryString()
Cookies[] getCookies()
HttpSession getSession()
HTTPprotocolspecificmethods
Later
-
8/22/2019 Begin Servlet
43/52
ServletResponse Interface
void setContentType(String type)
void setContentLength(int len)
ServletOutputStream
getOutputStream() PrintWriter getWriter()
Allows us to writeinto the responsestream
We have seenthis !
-
8/22/2019 Begin Servlet
44/52
HttpServletResponseInterface
void addCookies(Cookie c)
String addHeader(String name,Stringvalue)
void sendRedirect(String url)
void sendError(int ecode)
-
8/22/2019 Begin Servlet
45/52
Getting single parameters
In the doGet() method we can get the value enteredby the user in the html form using:String booktitle=request.getParameter(name);
Locate Books
Default is GET
book.war
-
8/22/2019 Begin Servlet
46/52
Question?
What will happen if your form has a post
method, and the servlet that the form calls has
only doGet() method?
Getting multiple parameters
-
8/22/2019 Begin Servlet
47/52
Getting multiple parameters
Select Colors:
RedGreen
Blue -
8/22/2019 Begin Servlet
48/52
Servlet to get multiple param
public class Colors extendsjavax.servlet.http.HttpServlet{public void doPost(javax.servlet.http.HttpServletRequestreq,javax.servlet.http.HttpServletResponseres)throws java.io.IOException,
javax.servlet.ServletException{java.io.PrintWriter out=res.getWriter();out.println("");
-
8/22/2019 Begin Servlet
49/52
Stringcolors[]=req.getParameterValues("color");
out.println("");for(int i=0;i
-
8/22/2019 Begin Servlet
50/52
Question?
What happens ifyou dont select
any of thecheckboxes?
-
8/22/2019 Begin Servlet
51/52
Servlet variable initialization
Initialization of servlet variables is generallydone in init() method.
In the normal class, initialization happens in theconstructor. But since the container calls the
constructor in this case, having parameterizedconstructor has no meaning.
The initialization values are passed to servletthrough DD and are available only from init()
method onwards. Therefore, the initialization is done in init()
method.Generally one never writes a constructor for a servlet!!
Si l Th dM d l I t f
-
8/22/2019 Begin Servlet
52/52
SingleThreadModel Interface In the servlet model that we have seen so far, a
single servlet processes multiple requestssimultaneously.
This means that the doGet and doPost methodsmust be careful to synchronize access to fields and
other shared data, since multiple threads may betrying to access the data simultaneously.
On the other hand, you can have your servletimplement the SingleThreadModel interface, as
below.public class YourServlet extendsHttpServlet implementsSingleThreadModel {...}
And say goodbye
to Scalability