- Servlets Tutorial
- Servlets - Home
- Servlets - Overview
- Servlets - Environment Setup
- Servlets - Life Cycle
- Servlets - Examples
- Servlets - Form Data
- Servlets - Client Request
- Servlets - Server Response
- Servlets - Http Codes
- Servlets - Writing Filters
- Servlets - Exceptions
- Servlets - Cookies Handling
- Servlets - Session Tracking
- Servlets - Database Access
- Servlets - File Uploading
- Servlets - Handling Date
- Servlets - Page Redirect
- Servlets - Hits Counter
- Servlets - Auto Refresh
- Servlets - Sending Email
- Servlets - Packaging
- Servlets - Debugging
- Servlets - Internationalization
- Servlets - Annotations
- Servlets Useful Resources
- Servlets - Questions and Answers
- Servlets - Quick Guide
- Servlets - Useful Resources
- Servlets - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Servlets - Interview Questions
Dear readers, these Servlets Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Servlets Programming. As per my experience, good interviewers hardly planned to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
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.
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.
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.
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.
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.
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.
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.
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
The destroy() method is called only once at the end of the life cycle of a servlet.
The init() method simply creates or loads some data that will be used throughout the life of the servlet.
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.
This method should be used to get data from server.
This method should be used to process data on the server.
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.
Servlets handles 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.
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.
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.
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.
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.
Get the object of PrintWriter using request.
PrintWriter out = response.getWriter();
Now print html.
out.println("Hello World");
We can use setStatus(statuscode) method of HttpServletResponse to send an authentication error.
// Set error code and reason. response.sendError(407, "Need authentication!!!" );
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.
This method generates a 302 response along with a Location header giving the URL of the new document.
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.
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.
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.
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.
This method is called by the web container to indicate to a filter that it is being placed into service.
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.
This method is called by the web container to indicate to a filter that it is being taken out of service.
Yes.
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.
Use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.
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>
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
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);
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.
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.
Session provides a way to identify a user across more than one page request or visit to 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.
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.
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();
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.
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.
setMaxInactiveInterval(int interval) of HTTPSession object specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
The simplest way of refreshing a web page is using method setIntHeader() of response object.
This means enabling a web site to provide different versions of content translated into the visitor's language or nationality.
This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
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 english locale for US.
Following is the method of request object which returns Locale object.
java.util.Locale request.getLocale()
Following method returns a name for the locale's country that is appropriate for display to the user.
String getDisplayCountry()
What is Next?
Further, you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)