Devjournals - Servlet
Devjournals - Servlet
Devjournals - Servlet
For example, to access an HTML page or image, we should use GET because it will always return the
same object but if we have to save customer information to database, we should use POST method.
Idempotent methods are also known as safe methods and we don’t care about the repetitive request from
the client for safe methods.
We can use ServletContext getMimeType() method to get the correct MIME type of the file and use it to set
the response content type. It’s very useful in downloading file through servlet from server.
Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like below
image.
6.What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by providing support for
dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own
servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods.
When implementing a generic service, we can extend the GenericServlet class provided with the Java
Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-
specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend
HttpServlet class. Servlet API hierarchy is shown in below image.
Servlets provide better performance that CGI in terms of processing time, memory utilization
because servlets uses benefits of multithreading and for each request a new thread is created,
that is faster than loading creating new Object for each request with CGI.
Servlets and platform and system independent, the web application developed with Servlet can
be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on
operating systems such as Windows, Linux, Unix, Solaris, Mac etc.
Servlets are robust because container takes care of life cycle of servlet and we don’t need to
worry about memory leaks, security, garbage collection etc.
Servlets are maintainable and learning curve is small because all we need to take care is
business logic for our application.
8.What are common tasks performed by Servlet Container?
Servlet containers are also known as web container, for example Tomcat. Some of the important tasks of
servlet container are:
ServletConfig is a unique object per servlet whereas ServletContext is a unique object for
complete application.
ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used
to provide application level init parameters that all other servlets can use.
We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext
that other servlets can use in their implementation.
12.What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or
another servlet in same application. We can also use this to include the content of another resource to the
response. This interface is used for inter-servlet communication in the same context.
13. void forward(ServletRequest request, ServletResponse response) – forwards the request from
a servlet to another resource (servlet, JSP file, or HTML file) on the server.
14. void include(ServletRequest request, ServletResponse response) – includes the content of a
resource (servlet, JSP page, HTML file) in the response.
We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use
ServletResponse getOutputStream() method to get the ServletOutputStream object reference.
We can extend these classes and override only specific methods we need to implement for custom request
and response objects. These classes are not used in normal servlet programming.
If there are any local variables in service methods, we don’t need to worry about their thread safety
because they are specific to each thread but if we have a shared resource then we can use
synchronization to achieve thread safety in servlets when working with shared resources.
The thread safety mechanisms are similar to thread safety in standalone java application, read more about
them at Thread Safety in Java.
Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.
a. Servlet Class Loading – When container receives request for a servlet, it first loads the class
into memory and calls it’s default no-args constructor.
b. Servlet Class Initialization – Once the servlet class is loaded, container initializes the
ServletContext object for the servlet and then invoke it’s init method by passing servlet config
object. This is the place where a servlet class transforms from normal class to servlet.
c. Request Handling – Once servlet is initialized, its ready to handle the client requests. For every
client request, servlet container spawns a new thread and invokes the service() method by
passing the request and response object reference.
d. Removal from Service – When container stops or we stop the application, servlet container
destroys the servlet class by invoking it’s destroy() method.
e. public void init(ServletConfig config) – This method is used by container to initialize the servlet,
this method is invoked only once in the lifecycle of servlet.
f. public void service(ServletRequest request, ServletResponse response) – This method is called
once for every request, container can’t invoke service() method until unless init() method is
executed.
g. public void destroy() – This method is invoked once when servlet is unloaded from memory.
h. User Authentication
i. HTML Hidden Field
j. Cookies
k. URL Rewriting
l. Session Management API
The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the
URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if
browser cookies are disabled.
We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the
request to another resource and we want to provide session information, we can use encodeRedirectURL()
method.
HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there
is no point of adding Cookie to request, there are no methods to set or add cookie to request.
However HttpServletResponse encodeRedirectUrl() method is used specially for encode the redirect URL
in response.
So when we are providing URL rewriting support, for hyperlinks in HTML response, we should use
encodeURL() method whereas for redirect URL we should use encodeRedirectUrl() method.
38.What is the effective way to make sure all the servlets are
accessible only when user has a valid session?
We know that servlet filters can be used to intercept request between servlet container and servlet, we can
utilize it to create authentication filter and check if request contains a valid session or not.
Check out Authentication Filter example at Servlet Filter Example.
If you application has a single entry point (user login), then you can do it in the first servlet request but if we
have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if database
is down or not configured properly, we won’t know until first client request comes to server. To handle these
scenario, servlet API provides Listener interfaces that we can implement and configure to listen to an event
and do certain operations.
Read more about different types of listeners and example at Servlet Listener.
Servlet API provides support for custom Exception and Error Handler servlets that we can configure in
deployment descriptor, the whole purpose of these servlets are to handle the Exception or Error raised by
application and send HTML response that is useful for the user. We can provide link to application home
page or some details to let user know what went wrong.
<error-page>
<error-code>404</error-code>
<location>/AppExceptionHandler</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/AppExceptionHandler</location>
</error-page>
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>com.foo.servlets.Foo</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
The load-on-startup value should be int, if it’s negative integer then servlet container will load the servlet
based on client requests and requirement but if it’s 0 or positive, then container will load it on application
startup.
If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will
be loaded first.
getServletContext().getRealPath(request.getServletPath())
getServletContext().getServerInfo()
Please read File Upload Servlet post that provide all the necessary details with example program to
upload and download file using servlets.
For complete example, please look into Servlet Database and Log4j Example.
Servlet Annotations: Prior to Servlet 3, all the servlet mapping and it’s init parameters were used to
defined in web.xml, this was not convenient and more error prone when number of servlets are huge in an
application.
Servlet 3 introduced use of java annotations to define a servlet, filter and listener servlets and init
parameters. Some of the important Servlet API annotations are WebServlet, WebInitParam, WebFilter and
WebListener. Read more about them at Servlet 3 annotations.
Web Fragments: Prior to servlet specs 3.0, all the web application configurations are required to be
present in the web.xml that makes it cluttered with lot of elements and chances of error increases. So
servlet 3 specs introduced web fragments where we can have multiple modules in a single web application,
all these modules should have web-fragment.xml file in META-INF directory. We can include all the
elements of web.xml inside the web-fragment.xml too. This helps us in dividing our web application into
separate modules that are included as JAR file in the web application lib directory.
Adding Web Components dynamically: We can use ServletContext object to add servlets, filters and
listeners programmatically. This helps us in building dynamic system where we are loading a component
only if we need it. These methods are addServlet(), addFilter() and addListener() defined in the servlet
context object.
Asynchronous Processing: Asynchronous support was added to delegate the request processing to
another thread rather than keeping the servlet thread busy. It can increase the throughput performance of
the application. This is an advance topic and I recommend to read Async Servlet tutorial.