- Servlet
act as a middle layer between a request coming from a Web browser and
application on the server.
- Advantages:
- Execute
within the Web server address space so no need to create a separate process
to handle each client request.
- Platform-independent
as written in Java
- Servlet
can be created using javax.servlet and javax.servlet.http packages
- Servlet
interface – defines life cycle methods
public interface Servlet {
public
void init(ServletConfig config)
throws
ServletException;
public
ServletConfig getServletConfig();
public
void service(ServletRequest req,
ServletResponse
res)
throws ServletException, IOException;
public
String getServletInfo();
public
void destroy();
}
- GenericServlet
class – provides Java Servlet API
public abstract class GenericServlet implements
Servlet,
ServletConfig,
Serializable {
public
GenericServlet() { ... }
public void
destroy() { ... }
public
String getInitParameter(String name) { ... }
public
Enumeration getInitParameterNames() { ... }
public
ServletContext getServletContext() { ... }
public
String getServletInfo() { ... }
public void
init(ServletConfig config) throws
ServletException
{ ... }
public void
init() throws ServletException { ...
}
public void
log(String msg) { ... }
public void
log(String message, Throwable t) { ... }
public
abstract void service(ServletRequest
req,
ServletResponse res) throws
ServletException,
IOException;
public String
getServletName() { ... }
}
- HttpServlet
class – provides method for handling HTTP-specific request like GET
(doGet) and POST (doPost).
public abstract class HttpServlet extends
GenericServlet {
protected
void doGet(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ... }
protected
long getLastModified(HttpServletRequest req) {
... }
protected
void doHead(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ... }
protected
void doPost(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
protected
void doPut(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
protected
void doDelete(HttpServletRequest
req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
protected
void doOptions(HttpServletRequest
req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
protected
void doTrace(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
private
static Method[] getAllDeclaredMethods(Class c)
{ ...}
protected
void service(HttpServletRequest req,
HttpServletResponse
resp) throws ServletException,
IOException
{ ...}
private
void maybeSetLastModified(HttpServletResponse
resp,
long lastModified) { ...}
public void
service(ServletRequest req, ServletResponse
res)
throws ServletException, IOException { ...}
}
- Servlet
lifecycle
- Initialization–
Servlet is initialized by calling init() method. It is called only once
when Servlet is first created. This happens when user invoke a URL corresponding
to the Servlet.
- Service
- For subsequent calls it creates a new thread and had off job to appropriate
doXXX() method through service() method.
- Destory
– Servlet is destroy at the end of lifecycle. destroy() method is called.
Summary: One time initialization
(if needed) goes in init(), all processing is done in doXXX() method, clean up
(if necessary) is does in destroy() method.
- Architecture
Diagram

- Sample
Application
- Create
Servlet Class
public class HelloServlet extends HttpServlet {
private Integer classVariable = 1;
private Integer servletInitilizationValue = 100;
@Override
public void init() throws ServletException {
servletInitilizationValue ++;
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Integer processVariable = 0;
classVariable*=2;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet at " +
request.getContextPath() + "</h1>");
out.println("<h2>processVariable: " +
processVariable++);
out.println("<h2> servletInitilizationValue: " +
servletInitilizationValue);
out.println("<h2>classVariable: " + classVariable);
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
public void destroy() {
System.out.println("Destroying");
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Output:
- For first call servletInitilizationValue will
display 101 and for subsequent call it remains 101 because servletInitilizationValue++
is called only once for first time.
- processVariable will be 0 for all call even we are
doing processVariable++ because every request will get there own copy of processVariable
- But classVariable will always print even number
for each call because only one instance of HelloServlet is created and instance
variable is shared by all request.
- From these output we can see that as Servlet is not thread safe we can safe
the data if put in method level instead of instance level.
- Map
URL to Servlet class
Add Servlet definition and mapping
in web.xml file
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
- Some request
header
- accept
- accept-charset
- accept-encoding
- accept-language
- content-length
- cookie
- host
- if-modified-since
- if-unmodified-since
- referrer
- user-agent
- Some
of the request object methods
- getParameter(Strring
parameterName): Get value of the parameter
- getParameterValues():
Get multiple values for same parameter (e.g checkbox)
- getParameterNames():
Get list of all parameters.
- getCookies()
- getSession()
- getLocale()
- getAuthType()
- getCharacterEncoding()
- getContentType()
- getContextPath()
- getHeader(String
name)
- getPathInfo()
- getProtocol()
- getQueryString()
- getServletPath():
part of URl that calls the JSP.
- getRemoteAddr():
client address
- getRemoteHost():
client host name
- getRemoteUser():
clinet login user
- isSecure()
- getContentLength()
- getServerPort(0:
port number which receive this request
- Some
response header
- Allow
- Cache-control
- Connection
- Content-encoding
- Content-language
- Content-length
- Content-type
- Expires
- Last-modified
- Location
- Refresh
- Retry-after
- Set-cookie
- Some
of response object methods
- encodeRedirectURL(String)
- encodeURL(String)
- addCookie(Cookie
cookie)
- sendError(…)
- sendRedirect(String)
- setBufferSize(int)
- setCharacterEncoding(String)
- setContentLength(int)
- setContentType(String)
- setHeader(String
name, String value)
- setLocale(Locale)
- setStatus(int)
- HTTP
Staus codes
- 100: continue
- 101: Switching protocols
- 2xx: Successful
- 3xx: Redirection
- 4xx: Client Error
- 5xx: Server Error
- Related
technology is Filters