You are on page 1of 40

J2EE

Servlets

Servlets
Java technology to write powerful server side programs that extends
the functionality of a Web Server
Provides platform-independent methods for building interactive web
applications
Act as a middle layer between a request coming from a Web browser
and databases or applications

Advantages
Requests execute as separate threads and as threads are light weight the
performance does not degrade
Object oriented and secure as it is purely written in java
Platform independent

J2EE

Building a Servlet
Packages

Servlet

javax.servlet
javax.servlet.http

Servlet: Interface

GenericServlet

defines life-cycle methods


to initialize a servlet
to service requests
to remove a servlet from the server

HttpServlet

GenericServlet: Abstract Class


Defines a generic, protocol-independent servlet
Implements the Servlet and ServletConfig interfaces

HttpServlet: Abstract Class


HTTP protocol specific

J2EE

TestServlet

Servlet Template
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Use "request" to read incoming HTTP headers
// and query data from HTML forms.
// Use "response" to specify the HTTP response status
// code and headers (e.g., the content type, cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser.
}
}

J2EE

Web App Deployment Descriptor(DD)

Is a xml file named web.xml


Root tag in web.xml is <web-app> </web-app>
Stored under the WEB-INF directory
Provides configuration and deployment information for the Web
components

Used to define the following


Servlet Declaration, Servlet Mappings and Servlet initialization parameters

Context initialization parameters


Security configuration including login-config, security-constraint, securityrole etc.
Welcome File list and Error Pages

J2EE

Using DD to map URLs to servlets


Tag used to define and map url to Servlets
<servlet>
maps internal name to fully-qualified class name

<servlet-mapping>
maps internal name to public URL name

J2EE

DEMO
1. CREATING DYNAMIC WEB PROJECT
2. CREATING A SIMPLE SERVLET (FIRSTSERVLET.JAVA)

3. WEB DEPLOYMENT DESCRIPTOR


4. RUNNING THE SERVLET IN A WEB BROWSER

J2EE

Servlet API

J2EE

Servlet Lifecycle and methods


Once

Once

For every request

A Servlet goes through Initialization, Service and destruction phase in its lifecycle
Initialization
Container initializes the servlet, when servlet receives the first client request or
during web application startup
Loads the servlet class, creates and runs the constructor to create Servlet instance
Calls the init() method to initialize the Servlet

init method is called by container only once during the life of a servlet
Initialization gives the servlet access to the ServletConfig and ServletContext
objects
Used for perform any setup processing

public void init(ServletConfig) throws ServletException


9

J2EE

Lifecycle Methods
Service
Most of a servlets life is spent running a service() method for a client request.
For every client request, container finds a thread, which executes the servlets
service() method
Service() method checks the HTTP Request method(GET,POST,etc) and calls doGet,
doPost ,etc based on the request method
Servlet should be initialized before it can service any client requests
Multiple threads may invoke the service() method of a given servlet at the same
time
public void Service(ServletRequest,ServletResponse) throws ServletException, IOException

Destruction
Destroys the servlet and release the resources
Container calls destoy() once during the life of a servlet

public void destroy()


10

J2EE

doGet() and doPost()


Programmer needs to override the doGet(), doPost, etc methods in the Servlet
based on the type of request
doGet() method is invoked by service() method when
User clicks on a link in a web page
User enters URL in browser address bar and presses enter
User submits a HTML form that has no method specified
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Servlet code
}

doPost() method is invoked by service() method when


User submits a HTML form with method specified as POST
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Servlet code
}

11

J2EE

HTTPServletRequest

Container creates a HttpServletRequest object


and passes it as an argument to the servlet's
service method

Used to provide information about the client


request to a servlet.

Contains the parameters sent by the client

Request object is valid only within the scope of a


servlets service method

Methods

getParameter(String pname) method returns the


value of a request parameter as a String

getInputStream() returns a ServletInput Stream,


which can be used to read the binary data sent
along with the request

12

J2EE

ServletRequest Interface
getParameter(String) : String
getParameterNames() : Enumeration
getParameterValues(String) : String[]
getAttribute(String) : Object
setAttribute(String,Object )
getInputStream() : ServletInputStream
//other methods

HttpServletRequest Interface
getCookies() : Cookie[]
getSession() : HttpSession
getHeader(String) : String
getHeaderNames() : Enumeration<String>
//other methods

HTTPServletResponse

Container creates a HttpServletResponse object


and passes it as an argument to the servlet's
service method

Used by the Servlet to send response to the


client. Servlet writes to the response object

Response object is valid only within the scope


of a servlets service method

Methods

13

ServletResponse Interface
getWriter() : PrintWriter
getOutputStream() :ServletOutputStream
setContentType(String)
setContentLength(int)
//other methods

setContentType(String) : Used to set the


contentType header of the response

HttpServletResponse Interface

getWriter() method returns a PrintWriter object


that can send character text to the client

getOutputStream() method returns


a ServletOutputStream suitable for writing binary
data in the response

addHeader(String name, String value) :


sendRedirect(location)
sendError(int) : void
setStatus(int) : void
addCookie(Cookie) : void
//other methods

J2EE

Common mime types

response.setContentType("text/html}

14

J2EE

15

J2EE

Request-Response processing cycle

Servlets are managed by the Web Container


User clicks a link that refers to the URL of a servlet
Web Server receives the request and passes it to the container
Container creates two objects, HttpServletRequest and
HttpServletResponse
Container locates the servlet from web.xml, loads and instantiates it,
and runs its init() method
Container creates/allocates a thread for that request. The Thread
executes servlets service() method. Request and response object are
passed to the service method
service() method calls the doGet() or doPost() method based on the
request method
doGet() or doPost() method is responsible for generating the response
The output from this method is stuffed into the response object
Container converts the response object to an HTTP response and sends
it to browser
16

J2EE

HANDLING FORM DATA


1. LOGINTEST.HTML
2. FORMSERVLET

3. REGISTER.HTML
4. REGISTERSERVLET

17

J2EE

Http Status codes

200 (OK)
Default for servlets

1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error

301 (Moved Permanently)


Requested document permanently moved
elsewhere
Browsers go to new location automatically
indicated in Location header
302 (Moved Temporarily`)
Requested document temporarily moved
elsewhere
Browsers go to new location automatically
indicated in location header
Servlets should use sendRedirect, not
setStatus, when setting this header.
401 (Unauthorized)
Browser tried to access password-protected
page without proper Authorization
404 (Not Found)
No such page. Servlets should use sendError
to set this

18

J2EE

Status Code and Errors


This method is used to set the return status code when there is no error
setStatus(int code);

resp.setStatus(HttpServletResponse.SC_FOUND);
SC_OK, SC_NOT_FOUND, etc . are constants in HttpServletResponse

sendError(int code, String message)


resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not Authorized");

Sends an error response to the client using the specified status code
If error page is defined for the error code in web.xml, Container displays
the page
If error page is not defined for the error code, Container generates a error
page
19

J2EE

Setting Response Headers

setHeader(String headerName, String headerValue)


resp.setHeader(Cache-Control, no-cache)

addHeader(String headerName, String headerValue)

Adds new occurrence of header instead of replacing

setDateHeader(String name, long millisecs)


setDateHeader(myDate,new Date());

Some Important Headers

Content-type
Cache-Control

Refresh

The number of seconds after which browser should reload page.

Expires

20

No-cache value prevents browsers from caching page

The time at which document should be considered out-of date and should no longer be cached

J2EE

ServletConfig Interface

ServletConfig
A servlet configuration object used by a
Container to pass information to a servlet
during initialization

getServletContext
getInitParameter
getInitParameterNames
getServletName
//other methods

One ServletConfig object per servlet

Container passes the ServletConfig object as an argument when calling servlets


init() method

ServletConfig stores the initialization parameters of the servlet, which are defined
in web.xml

Used to access the ServletContext

ServletConfig

interface is implemented by Servlet container provider

String name = getServletConfig().getServletName();

21

J2EE

Servlet Init Parameters


In the web.xml file:
<servlet>
<servlet-name>ParamTest</servlet-name>
<servlet-class>com.mycompany.ParamServlet</servlet-class>
<init-param>
<param-name>JDBC_URL</param-name>
<param-value>jdbc:oracle:thin@localhost:1521/XE</param-value>
</init-param>
</servlet>

In the servlet code:


String url = getServletConfig().getInitParameter(JDBC_URL);

22

J2EE

ServletContext

ServletContext Interface

One ServletContext object per web app


Created/destroyed when the web
application is started/shutdown

getInitParameter()
getContextPath()
getServerInfo()
getAttribute(String name)
setAttribute(String name, Object obj)
//other methods

Most commonly used to share the data across application, obtain URL
references to resources, dispatching a request etc..
Gives servlets, access to information about their Environment like the name
and version of the Container
Used as a kind of application bulletin-board, where messages (called
attributes) can be put for providing access to other parts of application

Available to all Servlets and JSPs in the web app


String server = getServletContext().getServerInfo();
23

J2EE

Context Init Parameters


In the DD (web.xml) file:
<context-param>
<param-name>adminEmail</param-name>
<param-value>support@mycompany.com</param-value>
</context-param>

In the servlet code:


String mail = getServletContext().getInitParameter(adminEmail);
String mail = getServletConfig().getServletContext().getInitParameter(adminEmail)

24

J2EE

GETTING DATA FROM DATABASE AND USING PARAMETERS

testcontext.html
TestContext Servlet
DataServlet

25

J2EE

More on Deployment Descriptor


<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletOne</servlet-name>
<servlet-class>com.mycompany.TestServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Directory Match
<url-pattern>/Test/*</url-pattern>
Extension match
<url-pattern>*.test</url-pattern>

26

<error-page>
<error-code>404</error-code>
<location>/CustomerErrorPage.html</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type>
<location>/html/IOError.html</location>x
</error-page>

J2EE

Redirection
Redirection used to redirect response to another resource which may be servlet, jsp
or html file.
Control is passed to the browser, which redirects the request to the url specified
Request can be passed within the same web application or to other web applications
on different servers
Done using sendRedirect(String url) of HttpServletResponse
Request
Servlet1

Browser

Servlet2

Redirect

Other
Website

resp.sendRedirect("http://www.manipalglobal.com");
resp.sendRedirect("servlet2");
Redirect Method sets status code to 302
It sets the url specified in the response header named location
27

J2EE

Servlet Chaining using RequestDispatcher


Servlet chaining means communication between two servlets
RequestDispatcher is used to FORWARD or INCLUDE a request from one
servlet to another Servlet/JSP within the same web application

RequestDispatcher object can be obtained in following two ways


request.getRequestDispatcher(String path)
path can be absolute or relative from current path

context.getRequestDispatcher(String path)
path can be only absolute path from context root

RequestDispatcher interface provides two methods.

28

forward(request,response)
include(request,response)

J2EE

Forward method
Allows a servlet to forward the request to another servlet/JSP/html
Request is forwarded to other resource permanently
Most commonly used way of transferring requests
Can be called only, if the response is not committed else an
IllegalStateException is thrown
RequestDispatcher dispatch = request.getRequestDispatcher(Servlet2);
dispatch.forward(request,response);

Browser

Request

Request
passing
Servlet1

Response

29

J2EE

Servlet2

Include Method
Request is transferred to other resource(Servlet/JSP/html)
temporarily
Other component processes the request and returns back the
control
ServletContext cntx=getServletContext();
RequestDispatcher dispatch=cntx.getRequestDispatcher(/Servlet2);
dispatch.include(request,response);

Request

Browser

Request

Servlet1
Response

30

Servlet2
Request

J2EE

Attributes
An attribute is an object bound to one of three objects given below
ServletContext
HttpServletRequest
HttpSession
Session is an object used to maintain conversational state with a client
The session persists across multiple requests from the same client

Name/value pair where the name is a String and the value is an Object
Method to add attributes
setAttribute(String name, Object value)

Method to get attribute


getAttribute(String name) : returns Object

Method to remove attributes


removeAttribute(String name)

31

J2EE

Scope of attributes
Context/Application attributes
All Servlets/JSPs in the application have access to this attribute
Any servlet/JSP can bind an object to context as a context attribute
Any servlet/JSP can remove an attribute bound to context

Session attributes
Accessible to web components which participate in a specific
HttpSession

Request attributes
Accessible to Servlets and JSPs processing the request
When a servlet transfers request to other Servlet/JSP, They will
have acccess to the request attribute

32

J2EE

Servlet1 sets an attribute and forwards the request to Servlet 2

Servlet2 gets the attribute


Country country = (Country) request.getAttribute("ctry");

DEMO : request dispatcher, forward and include, attributes


1. EmpLoginServlet
2. emplogin.html
3. LoginResult Servlet
4. testforward.html
5. TestForward Servlet
6. DisplayEmployee Servlet

33

J2EE

Session Management

Conversation consists of series of continuous request and response between client &
server

Session is a conversation between the server and a client

For Applications like online shopping, Railway Booking,Banking etc, state information
has to be saved between multiple requests, to maintain a conversation

Http is a stateless protocol and hence conversational State is not maintained

Session Management is a mechanism used to save the state of conversation between


multiple client requests

Following are ways used for managing sessions

34

Hidden form field


Cookies
HttpSession
URLRewriting

J2EE

Ways of Managing Session


Hidden field
a hidden textfield in the form is used for maintaining the
state
<input type="hidden" name=userId" value=1000">
<input type="hidden" name=role" value=admin">

Cookies
cookie is a small piece of information that is persisted
between the multiple client requests
Cookie is data stored as name/value pair
Cookies are maintained at client side
Limitations
Session Management fails if cookies is disabled by the browser
Only textual information can be set in Cookie
35

J2EE

Session Management with HttpSession


HttpSession object is used to hold the conversational state across multiple
requests(from the same client)
HttpSession Object is created and stored on the Server. Every Session is
assigned a unique identifier called a Session ID
The state of the conversation can be stored by binding attributes to the session
object
Session id is sent to browser in a cookie which is stored on the users computer
Browser sends the cookie back to the server every time a page is requested
The Container will match the session ID from the cookie to a session object
and used it for session management

36

J2EE

HttpSession Methods

request.getSession() / request.getSession(true)

Used for creating a session object


It will always return a session object
If there is no session object, it will create a new session
If a Session Object already exists, it will return the same.

Demo
1. Visit Servlet
2. order-form.html
3. ShowItems

request.getSession(false)

Used for an existing session object


It returns only an existing session object
In case it does not exist, it will return null.

session.setAttribute(String, object) :

session.getAttribute(String) :

session.invalidate() : used for discarding entire session

session.setMaxInactiveInterval(int interval)

Used for setting an attribute to a session

Used for reading an attribute

specifies the time, in seconds, before the servlet container will invalidate this session.
An interval of zero or negative value indicates that the session should never timeout

37

J2EE

Session tracking - URL Rewriting


URL rewriting appends the session ID to the URL for every page that's
requested
Server uses this session id to associate with a session
All pages must be dynamically written
Must rewrite every URL by using encodeURL() method of
HTTPResponse
The string returned by the methods will have the session ID appended
Works even if cookies are disabled by the browser. Server determines if
URL rewriting is required or not
HttpSession session = request.getSession();
out.println(<html><body>);
out.println(<a href=\ + response.encodeURL(/TestServlet) + \>click me</a>);
out.println(</body></html>);

38

J2EE

<session-config>
<session-timeout>300</session-timeout> 300 MINUTES
</session-config>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>

<welcome-file-list>
Used to define welcome files
<listener>
Used to define listener
<context-param>
Used to define Context parameters
<servlet>
Used to define servlet name and servlet class
<servlet-mapping>
Used to map the url to a servlet
<session-config>
Used to define session configuration
<login-config>
Used to define the type of authentication used in the
web application

39

J2EE

End

You might also like