Professional Documents
Culture Documents
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
HttpServlet
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
J2EE
<servlet-mapping>
maps internal name to public URL name
J2EE
DEMO
1. CREATING DYNAMIC WEB PROJECT
2. CREATING A SIMPLE SERVLET (FIRSTSERVLET.JAVA)
J2EE
Servlet API
J2EE
Once
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
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
J2EE
11
J2EE
HTTPServletRequest
Methods
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
Methods
13
ServletResponse Interface
getWriter() : PrintWriter
getOutputStream() :ServletOutputStream
setContentType(String)
setContentLength(int)
//other methods
HttpServletResponse Interface
J2EE
response.setContentType("text/html}
14
J2EE
15
J2EE
J2EE
3. REGISTER.HTML
4. REGISTERSERVLET
17
J2EE
200 (OK)
Default for servlets
1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error
18
J2EE
resp.setStatus(HttpServletResponse.SC_FOUND);
SC_OK, SC_NOT_FOUND, etc . are constants in HttpServletResponse
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
Content-type
Cache-Control
Refresh
Expires
20
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
ServletConfig stores the initialization parameters of the servlet, which are defined
in web.xml
ServletConfig
21
J2EE
22
J2EE
ServletContext
ServletContext Interface
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
J2EE
24
J2EE
testcontext.html
TestContext Servlet
DataServlet
25
J2EE
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
context.getRequestDispatcher(String path)
path can be only absolute path from context root
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)
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
33
J2EE
Session Management
Conversation consists of series of continuous request and response between client &
server
For Applications like online shopping, Railway Booking,Banking etc, state information
has to be saved between multiple requests, to maintain a conversation
34
J2EE
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
36
J2EE
HttpSession Methods
request.getSession() / request.getSession(true)
Demo
1. Visit Servlet
2. order-form.html
3. ShowItems
request.getSession(false)
session.setAttribute(String, object) :
session.getAttribute(String) :
session.setMaxInactiveInterval(int interval)
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
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