Servlets Technical Interview Questions Answers for Campus Placement


What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

What are the advantages of servlets over CGI?

Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.


What are the major tasks of servlets?

Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.


Explain servlet life cycle.

A servlet life cycle can be defined as the entire process from its creation till its destruction. The following are the paths followed by a servlet. − The servlet is initialized by calling the init () method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, the servlet is garbage collected by the garbage collector of the JVM.


When init() method of servlet gets called?

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.


When service() method of servlet gets called?

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.


When doGet() method of servlet to be called?

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.


When doPost() method of servlet to be called?

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.


When destroy() method of servlet gets called?

The destroy() method is called only once at the end of the life cycle of a servlet.


For what purpose init() method of a servlet is used?

The init() method simply creates or loads some data that will be used throughout the life of the servlet.


For what purpose destroy() method of a servlet is used?

This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.


For what purpose doGet() method of a servlet is used?

This method should be used to get data from the server.


For what purpose doPost() method of a servlet is used?

This method should be used to process data on the server.


Explain the working of the service() method of a servlet.

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method − public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ } The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.


How to read form data in servlet?

Servlets handle form data parsing automatically using the following methods depending on the situation − 

getParameter() − You call request.getParameter() method to get the value of a form parameter. 

getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.

getParameterNames() − Call this method if you want a complete list of all parameters in the current request.


How to read the name of all parameters in the servlet?

getParameterNames() method of HttpServletRequest returns complete list of all parameters in the current request. This method returns an Enumeration that contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.


How to read http header information in servlet?

We can use getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an Enumeration that contains the header information associated with the current HTTP request. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.


What is HTTPServletRequest class?

When a browser requests a web page, it sends a lot of information to the web server which can not be read directly because this information travel as a part of the header of HTTP request. HTTPServletRequest represents this HTTP Request.


What is HTTPServletResponse class?

when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. HTTPServletResponse represents this HTTP Response.

How to write html contents using servlets?

Get the object of PrintWriter using request. − PrintWriter out = response.getWriter(); Now print html. − out.println("Hello World");

How to send an authentication error from a servlet?

We can use setStatus(statuscode) method of HttpServletResponse to send an authentication error. // Set error code and reason. response.sendError(407, "Need authentication!!!" );


How to redirect a request from a servlet to another servlet?

Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or maybe because of load balancing, or for simple randomization. The simplest way of redirecting a request to another page is using the method sendRedirect() of the response object.

How sendRedirect method works?

This method generates a 302 response along with a Location header giving the URL of the new document.

How sendError method works?

This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client.

What are servlets filters?

Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes − To intercept requests from a client before they access a resource at the back end. To manipulate responses from the server before they are sent back to the client.


Name some of the servlets filters.

There are various types of filters suggested by the specifications − Authentication Filters. Data compression Filters. Encryption Filters. Filters that trigger resource access events. Image Conversion Filters. Logging and Auditing Filters. MIME-TYPE Chain Filters. Tokenizing Filters. XSL/T Filters That Transform XML Content.

How to do servlet filter mapping?

Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor.

For what purpose init() method of a filter is used?

This method is called by the web container to indicate to a filter that it is being placed into service.

For what purpose doFilter() method of a filter is used?

This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

For what purpose destroy() method of a filter is used?

This method is called by the web container to indicate to a filter that it is being taken out of service.

Can multiple filters be configured?

Yes.


Can filtering be done in an ordered way? If so then how to achieve it?

Yes. The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.


How to configure a central error handling page in servlets?

Use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.


How to configure a central error handler in servlets?

If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception − <error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page>


What are cookies?

Cookies are text files stored on the client's computer and they are kept for various information tracking purposes. Java Servlets transparently supports HTTP cookies.

           

How to create a cookie using servlet?

Setting cookies with servlet involves three steps − (1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , " / ? @ : ; (2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours. cookie.setMaxAge(60*60*24); (3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows − response.addCookie(cookie);


How to read a cookie using servlet?

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.


How to delete a cookie using servlet?

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps − Read an already existing cookie and store it in the Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie. Add this cookie back into the response header.


What is a session?

The session provides a way to identify a user across more than one page request or visit a Web site and to store information about that user. The session persists for a specified time period, across more than one connection or page request from the user.


What is URL rewriting?

You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://google.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.


How to create a session in servlet?

You would get the HttpSession object by calling the public method getSession() of HttpServletRequest, as below − // Create a session object if it is already not created. HttpSession session = request.getSession();


How to delete a session in servlet?

When you are done with a user's session data, you have several options −

Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with a particular key.

Delete the whole session − You can call public void invalidate() method to discard an entire session. Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.

Log the user out − On the servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.

How to update an attribute in session in servlet?

setAttribute(String name, Object value) of HTTPSession object binds an object to this session, using the name specified and can be used to update an attribute in session.

How to set session timeout in servlet?

setMaxInactiveInterval(int interval) of HTTPSession object specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

How to set auto page refresh in servlet?

The simplest way of refreshing a web page is using the method setIntHeader() of the response object.


What is internalization?

This means enabling a website to provide different versions of content translated into the visitor's language or nationality.


What is localization?

This means adding resources to a website to adapt it to a particular geographical or cultural region for example Hindi translation to a website.


What is a locale?

This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example "en_US" represents the English locale for the US.


How to detect locale in Servlets?

Following is the method of request object which returns Locale object. java.util.Locale request.getLocale()


How to get the country name in Servlets?

The following method returns a name for the locale's country that is appropriate for display to the user. String getDisplayCountry()
Previous Post Next Post