Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

25-Sep-21

Web Servers and Servlets Pre-requisites


• What is a URL?
• What is http?
• What is a stateless protocol?
• What is HTML?
• What is a Web-server?

Prof. Rama Chandra Rao Meka


RGMCET Nandyal

URL HTTP
• Stands for Uniform Resource Locator. • Stands for Hyper Text Transfer Protocol.
• The address that is typed in a web- • The most widely used protocol for
browser in order to load a page from a transferring data between web-browsers
remote location. and web-servers.
• Request and response to a typed URL is
in terms of the http protocol. • Is a stateless protocol implemented at the
Application Layer.
• Typically consists of the protocol, followed
by a “:” and an IP address of a machine • The default http port is : 80
followed by the file name to load.

HTML Web-server
• Stands for Hyper-text Markup Language. • A web server is a computer on the internet
• Most widely used language for data that hosts websites, serving pages to
transfer across the web. viewers upon request.
• Provides means to create structured • It has a unique IP address.
documents by denoting structural • Needs software to enable hosting of
semantics such as headings, paragraphs, pages, scripting etc.
lists, links etc. • Maps the path component of the URL into
a local file system resource.

1
25-Sep-21

Need for servlets How a CGI program works


• Early days of building dynamic content in a
client-server model
• One process for every client request.
• Communication with the web-server via
the Common Gateway Interface.
• CGI defines how the web server can
delegate generation of web-pages to a
console application.
• CGI Programs – C/C++, Perl etc.

CGI - disadvantages Enter servlets


• Very expensive in terms of resources – • Servlets are small programs (threads) that
memory and processor time. execute within the address space of a
• Very expensive in terms of database web-server.
operations – one connection • No separate process required for every
opened/closed for every client request. client request.
• Platform-dependent. • Platform-independent.
• Entire gamut of java class libraries
available to the servlet.

Servlet Lifecycle Servlet Lifecycle…


• URL typed and HTTP request sent across • Init() method may configure the servlet
the network. with initialization parameters.
• Request arrives at the web-server. • The “service()” method is invoked next.
This processes the http request. It can
• The request is mapped to a servlet. read parameters from the request and
• The servlet is loaded into the address formulate an http response. The “service()”
space of the web-server. method is called for every request.
• The web-server invokes the “init()” method • When the servlet has to be unloaded from
of the servlet. (one-time op at load-time) memory, the destroy() method is called.

2
25-Sep-21

Servlet Lifecycle Servlet Packages


• destroy() performs cleanup operations like • Two packages define the classes and
releasing of file handlers, persisting interfaces needed by servlets.
important information etc. • javax.servlet and javax.servlet.http.
• Memory allocated for the servlet is then • They are not part of the core Java
set aside for garbage collection. packages.
• They are standards extensions that are
provided by web-servers.

Apache Tomcat server Apache tomcat server..


• Open source implementation of Java • In order to be able to access the servlet
servlets and JSP classes and interfaces at compile and
• Default location is runtime, the servlet-api.jar needs to be
C:\\Program files\Apache Software present in the CLASSPATH.
Foundation\Tomcat 5.5
• The servlet-api.jar which contains all • For tomcat to be able to load a servlet, the
classes and interfaces to support servlets servlet needs to be present under its
is located in the “common\lib” directory “webapps” directory.

Apache tomcat server… Apache tomcat server…


• For the servlet to run successfully, entries • Ex: If the servlet is named “HelloServlet”, the
are also needed in the “web.xml” file. entries required are:
• <servlet>
• Two entries are needed here. One in the <servlet-name>HelloServlet</servlet-name>
section that defines servlets and another <servlet-class>HelloServlet</servlet-class>
</servlet>
in the section that defines servlet
mappings. • <servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>

3
25-Sep-21

A simple servlet Details…


• HelloServlet.java • GenericServlet – implements “Servlet”
interface. Provides default versions of
init(), service() and destroy().
• We need to override service() method.
• setContentType() establishes content type
of response.
• PrintWriter is a stream. Anything written to
this stream is sent to the client as part of
the http response.

Important Interfaces Important classes


• Servlet – declares init(), service(), destroy() • GenericServlet – implements Servlet and
• ServletConfig – to get initialization params ServletConfig
• ServletContext – info on servlet env • ServletInputStream – provides i/p stream
• ServletRequest – read data from client for reading requests from client
• ServletResponse – write data to client • ServletOutputStream – provides o/p
stream for writing responses to client
• ServletException - errors
• UnavailableException - errors

Servlet Interface ServletConfig Interface


• Declares the lifecycle methods of a • To obtain configuration data when the servlet is
loaded.
servlet.
• String getServletName() – returns the servlet
• String getServletInfo() – returns a string name
describing the servlet. • Enumeration getInitParameterNames() – returns
• ServletConfig getServletConfig() – returns an enumeration of initialization parameter
names.
the servlet configuration
• String getInitParameter(String name) – returns
the value of the initialization parameter named
“name”.

4
25-Sep-21

ServletContext Interface ServletRequest Interface


• Enables information retrieval about a • Enumeration getParameterNames() –
servlet’s environment. returns an enumeration of parameter
• Object getAttribute(String attr) – returns names passed in this request.
the server attribute named “attr”. • String getParameter(String name) –
• String getServerInfo() – returns info on the returns the value of the parameter named
server. “name” in the request.
• void setAttribute(String attr, Object val) –
sets the attribute named “attr” to the value • String getContentType() – return the
specified by “val” content type of the request

ServletResponse Interface GenericServlet class


• PrintWriter getWriter() – returns a • Implements Servlet and ServletConfig
PrintWriter object to write character data to Interfaces.
response.
• ServletOutputStream getOutputStream() –
returns a ServletOutputStream object to
write “binary” data to response.
• void setContentType() – sets the content
type of the response.

Exceptions
• ServletException – thrown when the • PostParameterServlet.java
servlet encounters a problem.

• UnavailableException – extends
ServletException. Thrown when the
requested server is not available.

5
25-Sep-21

The javax.servlet.http HttpServletRequest


• Special functionality built to specifically • Info on the http request from the client.
handle HTTP requests. • Important methods here are:
• The core interfaces provided for this – String getHeader(String fieldName)
purpose are: HttpServletRequest, – String getMethod()
HttpServletResponse, HttpSession and – String getQueryString()
the HttpSessionBindingListener. – Cookie[ ] getCookies()
– StringBuffer getRequestURL()

HttpServletResponse HttpServlet class


• void addCookie(Cookie obj) • Extends the GenericServlet class.
• void setHeader(String field, String value) • Defines various methods to handle
• void setStatus(int code) different kinds of http requests.
• void doGet() – to handle Http “GET”
requests.
• Void doPost() – to handle Http “POST”
requests.

Cookies
• HttpGetServlet.java • The “Cookie” class encapsulates a cookie.
• A cookie is stored on the client (browser)
side.
• It is useful in tracking user activities.
• If some information is necessary to be
passed between the client and server on
every request, it is ideal to send it via a
cookie.

6
25-Sep-21

Cookies… Cookies…
• With cookies, user does not have to enter the • Cookies are stored as “name-value” pairs
data each time he visits the same website. on the client machine.
• Typically a cookie is saved in a file on the client’s • In addition, the expiration date of the
machine, along with the domain and path of the cookie is also saved. The expiration date
webserver. decides when the cookie is to be deleted
• When the user enters a URL, the domain and from the client-machine.
path are checked and if a corresponding cookie • Cookies can be stored on the client
exists, it is sent silently to the web-server. machine by a servlet executing on the
server side.

Cookies… Cookies…
• The servlet can call the “addCookie()” • A few important methods are:
method to store a cookie on the client – String getName()
machine.
– String getValue()
• The addCookie() method belongs to the – void setMaxAge(int secs)
HttpServletResponse interface.
– int getMaxAge()
• The cookie is then sent as part of the
– String getDomain()
response header.
• Constructor: Cookie(String name, String
value)

Cookies.. Cookies…
• A word of caution with unfamiliar sites…. • SetCookiesServlet.java
• Cookies.html
• getCookiesServlet.java

7
25-Sep-21

http details http…


• Uses the Client-server model. • Example:
• Is Stateless. GET /path/to/file http/1.0
• Works on a request-response mechanism. Date: Fri, 31 Dec 1999 23:59:59 GMT
• Http message format: Content-type: text/html
– Initial line
– Header1 <Message body here>
– Header2
– <blank line>
– body

http methods - GET http methods - HEAD


• The GET method means retrieve whatever
information (in the form of an entity) is • The HEAD method is identical to GET
identified by the Request-URI. If the except that the server MUST NOT return a
Request-URI refers to a data-producing message-body in the response. The
process, it is the produced data which metainformation contained in the HTTP
shall be returned as the entity in the headers in response to a HEAD request
response. SHOULD be identical to the information
sent in response to a GET request.

http methods - POST http methods – POST…


• POST – The request URI is not a resource to retrieve;
• A POST request is used to send data to it's usually a program to handle the data
the server to be processed in some way, you're sending.
like by a CGI script. A POST request is – The HTTP response is normally program
different from a GET request in the output, not a static file.
following ways:
– There's a block of data sent with the request,
in the message body. There are usually extra
headers to describe this message body, like
Content-Type: and Content-Length:.

8
25-Sep-21

http methods – POST… http methods - DELETE


• Example • The DELETE method requests that the
POST /path/script.cgi HTTP/1.0 origin server delete the resource identified
From: frog@jmarshall.com by the Request-URI.
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-
urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

HttpSession HttpSession
• Enables a servlet to read and write state • The HttpSession object provides methods
information associated with an HTTP session. such as setAttribute(), getAttribute(),
• A new session can be created using the removeAttribute() and getAttributeNames()
getSession(true) call on a HttpServletRequest to manage bindings between objects and
object. With this call if a session already exists
names.
for the request object, it is returned. Else a new
HttpSession object is created and returned. • All servlets associated with a particular
• Provides a way of getting around the “stateless” client will share the session state.
nature of the Http protocol.

Session tracking example


• DateSession.java

You might also like