Servlet

What is the servlet ?

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

Therefore, the servlet is a Java programming language class that is used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.

What’s the difference between servlets and applets ?
Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.
What’s the advantages using servlets than using CGI ?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

What are the uses of Servlets ?

A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

What’s the Servlet Interface ?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.
Servlets–>Generic Servlet–>HttpServlet–>MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects. What are they ?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
How to destroy the session in servlets ?

We can destroy the session object by calling invalidate() method on the session object.

session.invalidate(), where session is the session object.
Can we call Servlet destory() from service() ?

Yes. We can call destroy() from within the service() as it is also a method like any other method. This can make sense sometimes, as destroy() will do whatever logic we have defined (cleanup, remove attributes etc.). Just bear in mind that simply calling destroy() would not unload the Servlet instance because the life cycle of Servlets in the program is managed by the Servlet Container.

What information that the ServletRequest interface allows the servlet access to ?

Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

What information that the ServletResponse interface gives the servlet methods for replying to the client ?

It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

If you want a servlet to take the same action for both GET and POST request, what should you do ?
Simply have doGet call doPost, or vice versa.
What is the servlet life cycle ?
Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when they shut down)
Which code line must be set before any of the lines that use the PrintWriter ?
setContentType() method must be set before transmitting the actual document.
How HTTP Servlet handles client requests ?

An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

What is the difference between ServletContext and ServletConfig ?
Both are interfaces.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet’s init() method.
The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
What are the differences between GET and POST service methods ?

A GET request is a request to get a resource from the server. Choosing GET as the “method” will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won’t show up in the URL bar. You can send much more information to the server this way – and it’s not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects.

GET is idempotent; so it is a safe method, whereas POST is non-idempotent method.
GET is used where we have a limited data to send in the header request URL whereas POST is used where we have sensitive and a large amount of data to send as a part of the body.
GET method is not secured because data is exposed in the URL and it can be easily bookmarked, POST is secured because data is sent in request body and it cannot bookmarked.
GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

What is the difference between GenericServlet and HttpServlet ?

GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.

What is different between web server and application server ?

A web server handles HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.
An example of a web server is Tomcat Server that has a servlet container, which is resposible for executing servlets and JSPs.

A web container also known as a Servlet container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.
Application Servers have a heavy-weight container susch as EJB and provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management support etc.

Which HTTP methods are idempotents and which HTTP methods are non-idempotents ?

A HTTP method is said to be idempotent if it returns the same result every time irrespective of the repetitive requests from clients. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return the same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

For example, we should use GET method to access an HTML page or image, because it will always return the same object but if we want to save customer information to database, we should use POST method.

What are common tasks performed by Servlet Container ?

Servlet containers are also known as web container, for example Tomcat Server. Some of the important tasks of servlet container are:

Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Container does important and complex tasks susch as build a server socket to listen for any request from web client, parse the request and generate response and all we need to do is focus on business logic for the applications.
Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlets susch as from the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management.
Multithreading Support: Container creates a new thread for every request to the servlet and provides request and response objects to the servlet. So servlets are not initialized for each request and saves time and memory.
JSP Support: JSP does not look like normal Java class but every JSP in the application is compiled by container and converted to Servlet and then container manages JSPs like other servlets.
Miscellaneous Task: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes developer’s life easier.

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.

There are two methods defined in this interface:
void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.
We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.
What is difference between PrintWriter and ServletOutputStream ?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to 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.

Can we get PrintWriter and ServletOutputStream both in a servlet ?

We cannot get instances of both PrintWriter and ServletOutputStream in a single servlet method, and if we try to invoke both getWriter() and getOutputStream() methods on response; we will get java.lang.IllegalStateException at runtime with message as other method has already been called for this response.

Do we need to override service() method ?

When servlet container receives requests from client, it invokes the service() method which in turn invokes the doGet() or doPost() method based on the HTTP request. So there is no use case where we need to override service() method. The whole purpose of service() method is to forward to request to corresponding HTTP method implementations.

Are servlets Thread Safe ? How to achieve thread safety in servlets ?

HttpServlet’s init() and destroy() methods are called only once in servlet life cycle, so these methods do not require thread safety. But service methods such as doGet() and doPost() are getting called in every client request and since servlet uses multithreading, we should find a way to provide thread safety in these methods. If we have any shared resource in service methods then we can use synchronization to achieve thread safety in servlets when working with shared resources.

What is the difference between ServletResponse sendRedirect() and RequestDispatcher forward() methods ?

forward() method is used to forward the same request to another resource whereas sendRedirect() method is used to send completely a new request. In sendRedirect(), web application returns the response to the client with the redirected URL (status code 302).

forward() is handled internally by the container whereas sendRedirect() is handled by browser.
forward() is generally recommended when resources are accessed in the same application because it is faster than sendRedirect() method that requires an extra network call.
In case of forward(), the browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect(), the URL in address bar changes to the forwarded resource.
forward() cannot be used to invoke a servlet in another context, we can only use sendRedirect() in this case.

What are servlet attributes and their scopes ?

Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in a web application. There are three scopes for servlet attributes – request, session and application scopes.

ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scopes respectively.

Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

why should we override only no-agrs init() method ?

If we have to initialize some resources before client’s requests processing, we should override init() method. When we override init(ServletConfig config) method, then we need to make sure superclass’s init(ServletConfig config) method is invoked first. That’s why GenericServlet provides another no-args init() method that gets called at the end of init(ServletConfig config) method. We should always utilize this method for overriding init() method to avoid any issue as we may forget to add super() call in overriding init method with ServletConfig argument.

What is URL Encoding ?

URL Encoding is the process of converting data into CGI form so that it can travel across the network without any issues. URL Encoding strip the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode) to encode a String. URL Decoding is the reverse process of encoding and we can use java.net.URLDecoder.decode(String str, String unicode) to decode the encoded string. For example roytuts’s blogs is encoded to roytuts%27s+blogs.

What are the different methods of session management in servlets ?

Session is a conversional state between client and server and it can consist of multiple requests and responses between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

  • User Authentication
  • HTML Hidden Field
  • Cookies
  • URL Rewriting
  • Session Management API

What is URL Rewriting ?

Servlet API provides support for URL rewriting that we can use to manage session when the cookie in client browser is disabled.

We can encode URL with HttpServletResponse’s encodeURL() method and if we need to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL() method.

How do Cookies work in Servlets ?

Cookies are used lots of time in web application for client-server communication and it is not something specific to Java. Cookies are text data sent by server to the client and it is saved at the client’s local machine.

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

HttpServletRequest’s getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there is no method to set or add cookie to request.

Similarly HttpServletResponse’s addCookie(Cookie c) method is provided to attach cookie in response header, there is no getter method for cookie.

What is the difference between encodeRedirectUrl and encodeURL ?

HttpServletResponse provides method to encode URL in HTML hyperlinks so that the special characters and white spaces are escaped and appends session id to the URL. It behaves similar to URLEncoder’s encode method with additional process to append jsessionid parameter at the end of the URL.

However HttpServletResponse’s encodeRedirectUrl() method is used specially for encoding the redirected URL in response.

Why do we have servlet filters ?

Servlet Filters are pluggable Java components that are used to intercept and process request before sending to servlet and process response after servlet is finished its task and before container sends the response back to the client.

Some common tasks of the filters are:

  • Logging request parameters to log files.
  • Authentication and autherization of request for resources.
  • Formatting of request body or header before sending it to the servlet.
  • Compressing the response data sent to the client.
  • Alter response by adding some cookies, header information etc

Why do we have servlet listeners ?

Think of a scenario when we want to initialize any attribute in ServletContext while the application starts up and before any request is made to the servlet. To handle these scenario, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.

How to get the actual path of servlet in server ?

We can use getServletContext().getRealPath(request.getServletPath()) to get the actual path of the servlet in file system.

How to get the server information in a servlet ?

We can use getServletContext().getServerInfo() to get the servlet information in a servlet through servlet context object.

How can we achieve transport layer security for web application ?

We can configure servlet container to use SSL for message communication over the network. To configure SSL on Tomcat, we need a digital certificate that can be created using Java keytool for development environment. For production environment, we should get the digital certificate from SSL certificate providers, for example, Verisign or Entrust.