Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

How to get country name in Servlets?

Answer»

Following method returns a name for the locale's country that is appropriate for display to the user.

String getDisplayCountry()
2.

How to detect locale in Servlets?

Answer»

Following is the method of request object which returns Locale object.

java.util.Locale request.getLocale() 
3.

What is internalization?

Answer»

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

4.

How to set auto page refresh in servlet?

Answer»

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

5.

How to set session timeout in servlet?

Answer»

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

6.

How to update an attribute in session in servlet?

Answer»

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.

7.

How to delete a session in servlet?

Answer»

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

  • Remove a particular attribute: You can call 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 public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.

  • Log the user out: 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.

8.

How to create a session in servlet?

Answer»

You would get 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();
9.

What is URL rewriting?

Answer»

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://tutorialspoint.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.

10.

How to delete a cookie using servlet?

Answer»

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 exsiting cookie and store it in Cookie object.

  • Set cookie age as zero using setMaxAge() method to delete an existing cookie.

  • Add this cookie back into response header.

11.

How to read a cookie using servlet?

Answer»

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.

12.

How to configure a central error handler in servlets?

Answer»

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>
13.

How to configure a central error handling page in servlets?

Answer»

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

14.

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

Answer»

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.

15.

Can multiple filters be configured?

Answer»

Yes.

16.

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

Answer»

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

17.

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

Answer»

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.

18.

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

Answer»

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

19.

How to do servlet filter mapping?

Answer»

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.

20.

Name some of the servlets filters?

Answer»

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.

21.

What are servlets filters?

Answer»

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 back end.

  • To manipulate responses from server before they are sent back to the client.

22.

How sendError method works?

Answer»

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.

23.

How sendRedirect method works?

Answer»

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

24.

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

Answer»

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 may be because of load balancing, or for simple randomization.The simplest way of redirecting a request to another page is using method sendRedirect() of response object.

25.

How to send an authentication error from a servlet?

Answer»

We can use setStatus(statuscode) method of HttpServletResponse to send an authentication error.

// Set error code and reason.response.sendError(407, "Need authentication!!!" );
26.

How to write html contents using servlets?

Answer»

Get the object of PrintWriter using request.

PrintWriter out = response.getWriter();

Now print html.

out.println("Hello World");
27.

What is HTTPServletResponse class?

Answer»

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.

28.

What is HTTPServletRequest class?

Answer»

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

29.

How to read http header information in servlet?

Answer»

We can use getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. 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.

30.

How to read name of all parameters in servlet?

Answer»

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.

31.

Explain working of service() method of a servlet.

Answer»

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.

32.

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

Answer»

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

33.

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

Answer»

This method should be used to get data from server.

34.

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

Answer»

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.

35.

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

Answer»

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

36.

When destroy() method of servlet gets called?

Answer»

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

37.

When doPost() method of servlet to be called?

Answer»

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

38.

When doGet() method of servlet to be called?

Answer»

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.

39.

When service() method of servlet gets called?

Answer»

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.

40.

When init() method of servlet gets called?

Answer»

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.

41.

Explain servlet life cycle.

Answer»

A servlet life cycle can be defined as the entire process from its creation till the 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, servlet is garbage collected by the garbage collector of the JVM.

42.

What are the major tasks of servlets?

Answer»

Servlets perform the following major tasks:

  • 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.

43.

What are the advantages of servlets over CGI?

Answer»

Servlets offer several advantages in comparison with the 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.

  • Servlets are platform-independent because they are written in Java.

  • 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.