basicservlet_1[1]
TRANSCRIPT
-
8/8/2019 BasicServlet_1[1]
1/106
Servlet Basics
-
8/8/2019 BasicServlet_1[1]
2/106
What is A Servlet?
Servlets are pieces of Java source code that addfunctionality to a web server in a manner similar to theway applets add functionality to a browser.
Servlets are server-side software components, writtenin Java and run inside a server .
Servlets are loaded and executed within the JavaVirtual Machine (JVM) of the server, in much the same
way that applets are loaded and executed within theJRE of the Web client.
Works on request /response model
-
8/8/2019 BasicServlet_1[1]
3/106
Servlet
-
8/8/2019 BasicServlet_1[1]
4/106
Multitiered J2EE applications
-
8/8/2019 BasicServlet_1[1]
5/106
J2EE Components
The J2EE specification defines the following J2EE
components:
Application clients and applets are components that run onthe client.
Java Servlet and JavaServer Pages (JSP ) technology
components are web components that run on the server.
Enterprise JavaBeans (EJB ) components (enterprise beans)
are business components that run on the server.
-
8/8/2019 BasicServlet_1[1]
6/106
Where are Servlet and JSP?
-
8/8/2019 BasicServlet_1[1]
7/106
J2EE Container
-
8/8/2019 BasicServlet_1[1]
8/106
First Servlet Code
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType("text/html");PrintWriter out = response.getWriter();
out.println("Hello World!");
}
...
}
-
8/8/2019 BasicServlet_1[1]
9/106
CGI versus Servlet
-
8/8/2019 BasicServlet_1[1]
10/106
CGI versus Servlet
Main Process
Java Servlet-based Web Server
JVM
Servlet1Servlet1
Servlet2Servlet2
Requ
est forServlet 1 Thread
Request for
Servlet 1
ThreadRequest for
Servlet 2
Thread
-
8/8/2019 BasicServlet_1[1]
11/106
CGI versus Servlet
-
8/8/2019 BasicServlet_1[1]
12/106
Advantages of Servlet
No CGI limitations
Abundant third-party tools and Web servers
supporting Servlet
Access to entire family of Java APIs
Reliable, better performance and scalability
Platform and server independent
Secure
-
8/8/2019 BasicServlet_1[1]
13/106
HTTP Basics
HTTP is a simple, stateless protocol .
A client makes a request and the web serverresponds.
For example:GET /intro.html HTTP/1.0
the client sends an HTTP command, a method, thattells the server the type of action .
also specifies the address of a document (a URL) andthe version of the HTTP protocol it is using.
-
8/8/2019 BasicServlet_1[1]
14/106
Http Basics cont..
After the client sends the request, the server
processes it and sends back a response.
For example :
HTTP/1.0 200 OK
the response specifies the version of theHTT
Pprotocol the server is using, a status code, and a
description of the status code.
-
8/8/2019 BasicServlet_1[1]
15/106
HTTP GET and POST
The most common client requests
HTTP GET & HTTP POST
GET requests:
User entered information is appended to the URL ina query string
Can only send limited amount of data
POST
requests: User entered information is sent as data (notappended to URL)
Can send any amount of data
-
8/8/2019 BasicServlet_1[1]
16/106
Demo
-
8/8/2019 BasicServlet_1[1]
17/106
GET Request
-
8/8/2019 BasicServlet_1[1]
18/106
POST Request
-
8/8/2019 BasicServlet_1[1]
19/106
Servlet Request and Response Model
-
8/8/2019 BasicServlet_1[1]
20/106
What are Servlets?
Servlets are programs that run on a Web server .
Act as a middle layer between a request coming from
a Web browser or otherHTTP client and databases or
applications on the HTTP server.
-
8/8/2019 BasicServlet_1[1]
21/106
What Servlet does?
Servlets job is to:
Read any data sent by the user.
Look up any other information about the request that is
embedded in the HTTP request. Generate the results.
Format the results inside a document.
Set the appropriate HTTP response parameters.
Send the document back to the client.
-
8/8/2019 BasicServlet_1[1]
22/106
Servlet Request and Response
model
-
8/8/2019 BasicServlet_1[1]
23/106
Requests and Responses
What is a request?
Information that is sent from client to a server
* Who made the request
* What user-entered data is sent* Which HTTP headers are sent
What is a response?
Information that is sent to client from a server
* Text(html, plain) or binary(image) data
* HTTP headers, cookies, etc
-
8/8/2019 BasicServlet_1[1]
24/106
Servlet API
-
8/8/2019 BasicServlet_1[1]
25/106
Servlet API
Servlets use classes and interfaces from twopackages :
Generic (protocol-independent) servlet classes:
javax.servlet.
HTTP specific servlet classes:
javax.servlet.http.
-
8/8/2019 BasicServlet_1[1]
26/106
Servlet Classes and Interfaces
-
8/8/2019 BasicServlet_1[1]
27/106
Servlet
Servlet does not have a main() method.
Each time the server dispatches a request to a servlet
it invokes the servlets service() method.
-
8/8/2019 BasicServlet_1[1]
28/106
Servlet API
Servlet Interface (javax.servlet.Servlet)
This interface has the servlet life cycle methods .
GenericServlet Class(javax.servlet.GenericServlet)
A protocol independent servlet should subclass
this servlet & should override the service()
method.
HttpServlet Class(javax.servlet.http.HttpServlet)
An abstract class that implements the service()method to reflect the HTTPness of the servlet .
The subclass should not override the service
method .
-
8/8/2019 BasicServlet_1[1]
29/106
Calling service() method
-
8/8/2019 BasicServlet_1[1]
30/106
Calling doGet() / doPost()
-
8/8/2019 BasicServlet_1[1]
31/106
Writing Hello World
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponseres)throws ServletException, IOException {
res.setContentType("text/html");PrintWriter out = res.getWriter();out.println("");out.println("Hello World");
out.println("");out.println("Hello World");out.println("");}
}
-
8/8/2019 BasicServlet_1[1]
32/106
Servlet Life Cycle
-
8/8/2019 BasicServlet_1[1]
33/106
Servlet Life Cycle
-
8/8/2019 BasicServlet_1[1]
34/106
First Client Request
When the first client request comes :
Container creates the servlet instance .
Invokes its init() method .
Later, each user request results in a thread that calls theservice() method of the previously created instance.
The service method then calls doGet(), doPost(), or anotherdoXxxmethod depending on the type ofHTTP request itreceived.
Finally, when the server decides to unload a servlet, it first callsthe servlets destroy() method.
-
8/8/2019 BasicServlet_1[1]
35/106
Servlet Life Cycle
-
8/8/2019 BasicServlet_1[1]
36/106
Servlet Life Cycle methods
init() Executed once when the servlet is first loaded.
Not called for each request.
Perform any one time set-up code in this method.
service()
Called in a new thread by server for each request. Dispatches to doGet, doPost, etc.
doGet(), doPost(), doXxx()
Handles GET, POST, etc. requests.
Override these to provide desired behavior.
destroy()
Called when server deletes servlet instance.
Perform any clean-up, and save data to be read by the next init().
-
8/8/2019 BasicServlet_1[1]
37/106
service() method
-
8/8/2019 BasicServlet_1[1]
38/106
doGet() / doPost()
-
8/8/2019 BasicServlet_1[1]
39/106
First Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("First Servlet");out.println(Wel-Come!");
}
}
-
8/8/2019 BasicServlet_1[1]
40/106
-
8/8/2019 BasicServlet_1[1]
41/106
Calling service method()
Calls the servlets service() method passing the
request and response objects as arguments .
Based on the Http method, service() method calls the
doGet()/doPost() method passing the request and
response objects as arguments .
-
8/8/2019 BasicServlet_1[1]
42/106
Sending response to client
Servlet uses the response object to write out to client
through the container .
The client gets the response .
-
8/8/2019 BasicServlet_1[1]
43/106
Servlet Request
-
8/8/2019 BasicServlet_1[1]
44/106
Servlet Request
Contains data passed from client to servlet .
All servlet requests implement ServletRequest interface which
defines methods for accessing Client sent parameters , Object-
valued attributes etc..
-
8/8/2019 BasicServlet_1[1]
45/106
Getting Client Sent
Parameters
A request can come with any number of parameters
Parameters are sent from HTML forms:
GET: as a query string, appended to a URL POST: as encoded POST data, not appeared in the URL
getParameter( paramName )
Returns the value of paramName
Returns null if no such parameter is present
Works identically for GET and POST requests
-
8/8/2019 BasicServlet_1[1]
46/106
HTTPServletRequest
Contains data passed from HTTP client to HTTP servlet
Created by servlet container and passed to servlet as aparameter ofdoGet() ordoPost() methods
HttpServletRequest is an extension ofServletRequestand provides additional methods for accessing
HTTP request URL
Context, servlet, query information
Misc.HTT
P Request header information Authentication type & User security information
Cookies
Session
-
8/8/2019 BasicServlet_1[1]
47/106
URI - Uniform Resource Identifier
Identifies the resource on host machine and
access method for that resource.
E.g. http://www.yahoo.com/index.html
3 parts
Scheme or protocol.
DNS name of the host.
File name on the host.
-
8/8/2019 BasicServlet_1[1]
48/106
HTTP Request URL
Contains the following parts
http://[host]:[port]/[request path]?[query
string]
-
8/8/2019 BasicServlet_1[1]
49/106
HTTP Request URL:
[request path]
http://[host]:[port]/[request path]?[querystring]
[request path] is made of
Context: /
Servlet name: /
Examples
http://localhost:7001/hello1/greeting
http://localhost:7001/hello1/greeting.jsp
-
8/8/2019 BasicServlet_1[1]
50/106
HTTP Request URL:
[query string]
http://[host]:[port]/[request path]?[query string]
[query string] are composed of a set of parameters andvalues that are user entered
Two ways query strings are generated A query string can explicitly appear in a web page
ClickHere
String bookId = request.getParameter( Add );
A query string is appended to a URL when a form witha GETHTTP method is submitted
http://localhost/hello1/greeting?username=Monica+Clinton
String userName=request.getParameter(username)
-
8/8/2019 BasicServlet_1[1]
51/106
Context, Path, Query,
ParameterMethods
String getContextPath()
String getQueryString()
String getParameter(String paramName)
String[] getParameterValues(String paramName)
Enumeration getParameterNames()
-
8/8/2019 BasicServlet_1[1]
52/106
HTTP Request
Client sends a request
Request method, URI, and protocol version.
Request headers
request modifiers, client information.
A blank line.
Optional body contents.
-
8/8/2019 BasicServlet_1[1]
53/106
HTTP Request Headers
HTTP requests include headers which provide extra informationabout the request
Example ofHTTP 1.1 Request:
host : localhost:8080
user-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; InfoPath.1;.NET CLR 3.0.04506.648)
referrer:http://localhost:8080/ServletProject/HandleRequestDataForm.html
-
8/8/2019 BasicServlet_1[1]
54/106
HTTP HeaderMethods
String getHeader(java.lang.String name)
value of the specified request header as String
java.util.Enumeration getHeaders(java.lang.String name)
values of the specified request header java.util.Enumeration getHeaderNames()
names of request headers
int getIntHeader(java.lang.String name)
value of the specified request header as an int
-
8/8/2019 BasicServlet_1[1]
55/106
Servlet Response
-
8/8/2019 BasicServlet_1[1]
56/106
What is Servlet Response?
Contains data passed from servlet to client
All servlet responses implement ServletResponseinterface
Retrieve an output stream
Indicate content type
Indicate whether to buffer output
Set localization information
HttpServletResponse extends ServletResponse
HTTP response status code
Cookies
-
8/8/2019 BasicServlet_1[1]
57/106
Responses
-
8/8/2019 BasicServlet_1[1]
58/106
Http Response
Server responds back with
Status line including message protocol version and astatus code.
Several message headers
server information, entity meta-information. Optional body contents.
-
8/8/2019 BasicServlet_1[1]
59/106
Header in HTTP Response
-
8/8/2019 BasicServlet_1[1]
60/106
Why HTTP Response Headers?
Give forwarding location
Specify cookies
Supply the page modification date
Instruct the browser to reload the page after adesignated interval
Give the file size so that persistent HTTP connectionscan be used
Designate the type of document being generated .
Methods for Setting Arbitrary
-
8/8/2019 BasicServlet_1[1]
61/106
Methods for Setting Arbitrary
Response Headers
public void setHeader( String headerName, StringheaderValue)
public void setDateHeader( String name, long millisecs)
public void setIntHeader( String name, int headerValue)
addHeader, addDateHeader, addIntHeader
setContentType
setContentLength
addCookie
sendRedirect
-
8/8/2019 BasicServlet_1[1]
62/106
Body in HttpResponse
-
8/8/2019 BasicServlet_1[1]
63/106
Writing a Response Body
A servlet almost always returns a response body
Response body could either be a PrintWriteror a
ServletOutputStream
PrintWriter
Using response.getWriter()
For character-based output
ServletOutputStream Using response.getOutputStream()
For binary (image) data
-
8/8/2019 BasicServlet_1[1]
64/106
Web Application Deployment
-
8/8/2019 BasicServlet_1[1]
65/106
Web Application
A Web Application is ,
a collection of servlets,JSP,HTML documents, imagesand other web resources that are setup in such a wayas to be portably deployed across any servlet enabled
web server.
Each Web Application consists of
Configuration file web.xml Static files and JSP
Class files.
-
8/8/2019 BasicServlet_1[1]
66/106
Tomcat Structure
-
8/8/2019 BasicServlet_1[1]
67/106
Apache Tomcat Server
Tomcat can handle Web pages, Servlets, and JSPs
Includes a servlet container used for testing and
deploying servlets .
Tomcat is open source (free)
-
8/8/2019 BasicServlet_1[1]
68/106
Configuring Tomcat
By editing server.xml (conf/server.xml), we canchange the port where Tomcat will listen forHTTPrequests.
By default the port is 8080.
-
8/8/2019 BasicServlet_1[1]
69/106
Web Application : Static parts
-
8/8/2019 BasicServlet_1[1]
70/106
Web Application : WEB-INF
-
8/8/2019 BasicServlet_1[1]
71/106
WEB-INFDirectory
web.xml :
Web application deployment descriptor that contains meta-data forthe web application.
used by the container while loading the web application.
File is always located in the WEB-INF directory of the webapplication.
-
8/8/2019 BasicServlet_1[1]
72/106
web.xml and WEB-INF
classes :
A directory that contains server-side classes: servlets,
utility classes, and JavaBeans components
lib :A directory that contains JAR archives of libraries (tag libraries
and any utility libraries called by server-side classes)
The WEB-INF directory is kept hidden from the users of the Webapplication.
-
8/8/2019 BasicServlet_1[1]
73/106
WEB-INF : Forbidden
Steps for creating a web
-
8/8/2019 BasicServlet_1[1]
74/106
Steps for creating a web
application Create a directory called MyWebapp in the /webapps folder of your
Tomcat
Create a sub-directory WEB-INF inside MyWebApp.
Inside WEB-INF create a web.xml file as shown below :
Create a classes sub-directory to place the serverside classes .
-
8/8/2019 BasicServlet_1[1]
75/106
JAR and WAR
Java Archive file is a convenient method for
consolidating a set of Java classes into one
compressed portable file.
Any JAR file in the WEB-INF/lib directory of a web
application is made for use by the code in the same
web app.
-
8/8/2019 BasicServlet_1[1]
76/106
WAR
Web Application Resource files are similar to JAR files but are
used to consolidate the entire web application into one
compressed portable file.
-
8/8/2019 BasicServlet_1[1]
77/106
ServletConfig Interface
-
8/8/2019 BasicServlet_1[1]
78/106
init() method
init() method is used to perform servlet initialization .
There are two versions of init:
one that takes no arguments one that takes a ServletConfig object as an argument
The first version of init looks like this:
public void init() throws ServletException {// Initialization code...
}
-
8/8/2019 BasicServlet_1[1]
79/106
init(ServletConfig config)
The second version of init is used when the servletneeds to read server-specific settings before it cancomplete the initialization.
The second version of init looks like this:
public void init(ServletConfig config)throws ServletException {super.init(config); //this is necessary// Initialization code...
}
-
8/8/2019 BasicServlet_1[1]
80/106
Which init to use ?
If the init(ServletConfig config) is used then it isimportant to have super.init(config) as its first line. You can use this.servletconfig = config to store the
ServletConfig object.
The no-arg init() method is a convenience methodprovided by the API.
You can use getServletConfig() method to get theServletConfig object.
-
8/8/2019 BasicServlet_1[1]
81/106
init method
ServletConfig parameter used in second version providedconfiguration information to the servlet.
super.init(config) call passes the config object to theGenericServlet
The GenericServlet class use the config parameter to implementthe ServletConfig Interface .
Thus a servlet can invoke ServletConfig methods.
-
8/8/2019 BasicServlet_1[1]
82/106
init method contd..
GenericServlet class also supports no-arg init() method .
When the first version , no-argument init() method isimplemented:
ServletConfig and GenericServlet handling is taken care inbackground .
Web server still calls a servlets init(ServletConfig config)method at initialization time .
GenericServlet then passes the call to no-arg overridden init()method
-
8/8/2019 BasicServlet_1[1]
83/106
ServletConfig methods
ServletConfig methods String getInitParameter(String name)
Enumeration getInitParameterNames()
ServletContext getServletContext()
String getServletName()
Assigning Servlet Initialization
-
8/8/2019 BasicServlet_1[1]
84/106
Assigning Servlet Initialization
Parameters
InitTest
moreservlets.InitServlet
firstName
abc
Reading Servlet Initialization
-
8/8/2019 BasicServlet_1[1]
85/106
Reading Servlet Initialization
Parameters
public class InitServlet extends HttpServlet {
private String firstName, emailAddress;
public void init() {
ServletConfig config = getServletConfig();firstName =config.getInitParameter("firstName");
emailAddress =config.getInitParameter("emailAddress");
}
public void doGet() { }}
-
8/8/2019 BasicServlet_1[1]
86/106
ServletContext class
S l tC t t
-
8/8/2019 BasicServlet_1[1]
87/106
ServletContext
Context init parameters are available to entire web application.
Any servlet in the application has access to the context init
parameter.
There is one ServletContext object per web application .
S tti t
-
8/8/2019 BasicServlet_1[1]
88/106
Setting parameters
web.xml element: context-param
support-email
Invoking context parameter from a servlet :
ServletContext context=getServletContext();
out.println(context.getInitParameter(support-email ));
-
8/8/2019 BasicServlet_1[1]
89/106
Including, Forwarding, Redirecting
to other Web resources
Including Forwarding Redirecting
-
8/8/2019 BasicServlet_1[1]
90/106
Including, Forwarding, Redirecting
to other Web resources
You do not want to deal with the response rather want another
web component to handle the request ?
There are two options to follow :
Redirect the request to a completely different URL.
Dispatch the request to some other component in the web
application .
-
8/8/2019 BasicServlet_1[1]
91/106
Redirecting the Request
A client types a URL into the browser and a servlet is located :
Suppose the servlet decides to send the request to a completely
different URL .
It calls sendRedirect(NewURL) on the response . the client gets the response and makes a new request for the
NewURL .
The specific web component is called ,the request gets fulfilled
and the response is send back to the client.
Redirect makes the browser do the work.
-
8/8/2019 BasicServlet_1[1]
92/106
Redirecting a Request
Programming model for directing a request
public void sendRedirect(String url)
if(doTheWork){
//handle the request
} else {
response.sendRedirect(http://www.oreilly.com);
}
You can use Relative URLs You cant do a sendRedirect() after writing to the
response
-
8/8/2019 BasicServlet_1[1]
93/106
Relative URLs
Two waysOriginal :
http://www.wickedlysmart.com/myApp/cool/bar.doIf in Servlet (without forward slash(/ )):
sendRedirect(foo/stuff.html);
Container builds the full URL as :
http://www.wickedlysmart.com/myApp/cool/foo/stuff.html
OR
If in Servlet (with forward slash(/)):sendRedirect(/foo/stuff.html);
Container builds the full URL as :
http://www.wickedlysmart.com/myApp/foo/stuff.html
U i R tDi t h
-
8/8/2019 BasicServlet_1[1]
94/106
Using RequestDispatcher
A client types a URL into the browser and a servlet is located :
Suppose the servlet decides to send the request to a completelydifferent URL .
It calls :RequestDispatcher view =
request.getRequestDispatcher(abc.jsp);
view.forward(request,response);
abc.jsp takes over the response .
The client gets the response in usual way , the user does not knowthat the JSP generated the response .
-
8/8/2019 BasicServlet_1[1]
95/106
RequestDispatcher
Request dispatch does the work on the server side i.e.
transparent to the browser .
The method getRequestDispatcher(String path) in class
ServletRequest helps dispatching the request
public RequestDispatcher getRequestDispatcher(String path)
-
8/8/2019 BasicServlet_1[1]
96/106
RequestDispatcherMethods
void forward(ServletRequest request,
ServletResponse
response)
void include(ServletRequest request,
ServletResponse
response)
Forward with RequestDispatcher
-
8/8/2019 BasicServlet_1[1]
97/106
Example
public void doPost(HttpServletRequest req, HttpServletResponseres)
{
String userid = req.getParameter("userid");
String password = req.getParameter("password");
if( userid != null && password != null &&password.equals(users.get(userid)) )
{
req.setAttribute("userid", userid);
ServletContext ct = getServletContext();
RequestDispatcher rd =
ct.getRequestDispatcher("/servlet/AccountServlet");rd.forward(req, res);
return;
}
else
-
8/8/2019 BasicServlet_1[1]
98/106
RequestDispatcher Example
Cont..
{
RequestDispatcher rd =
req.getRequestDispatcher("../login.html");
rd.forward(req, res);return;
}
}
-
8/8/2019 BasicServlet_1[1]
99/106
Including another Web
Resource
When to Include another Web
-
8/8/2019 BasicServlet_1[1]
100/106
When to Include another Web
resource?
When it is useful to add static or dynamic
contents already created by another web
resource
Adding a banner content or copyright information inthe response returned from a Web component
-
8/8/2019 BasicServlet_1[1]
101/106
Example: Including a Servlet
RequestDispatcher dispatcher
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
dispatcher.include(request, response);
}
-
8/8/2019 BasicServlet_1[1]
102/106
Scope Objects
S Obj t
-
8/8/2019 BasicServlet_1[1]
103/106
Scope Objects
Enables sharing information among collaborating web
components via attributes maintained in Scope objects
Attributes are name/object pairs
Attributes maintained in the Scope objects are
accessed with
getAttribute() & setAttribute()
3 Scope objects are defined
Web context, session, request
S Obj t Cl
-
8/8/2019 BasicServlet_1[1]
104/106
Scope Objects : Class
Web context (ServletConext)
javax.servlet.ServletContext
Session
javax.servlet.http.HttpSession
Request
subtype of javax.servlet.ServletRequest:
javax.servlet.http.HttpServletRequest
-
8/8/2019 BasicServlet_1[1]
105/106
Methods for Scope Objects
Object getAttribute(String name)
void setAttribute(String name, Object value)
Enumeration getAttributeNames();
Example: Getting Attribute Value
-
8/8/2019 BasicServlet_1[1]
106/106
Example: Getting Attribute Value
from ServletContext
ServletContext context=getServletContext();
Context.setAttribute(ContextAttribute , SomeVal);
String val=
(String)context.getAttribute("ContextAttribute");