Servlet Interview Questions

1 - What are the new features added to Servlet 2.5?
Following are the changes introduced in Servlet 2.5:
  • Support for annotations
  • Loading the class
  • A handful of removed restrictions
  • Some edge case clarifications
  • A new dependency on J2SE 5.0
  • Several web.xml conveniences

2 - What are difference between Servlet and CGI?
Servlet
CGI
The Servlets runs as a thread in the web-container
instead of in a seperate OS process.
CGI script runs as a new OS process for each request.
Only one object is created first time when first
request comes, other request share the same object.
CGI create object every time when request comes to it.
Servlet is platform independent CGI is platform dependent.
Servlet is fast. CGI is slow.

3 - What's the difference between GenericServlet and HttpServlet?
GenericServlet
HttpServlet
Only for HTTP protocol. General for all protocol.
Inherit GenericServlet class. Implements Servlet interface.
Use doPost, doGet method instead of
service method.
Use service method.

4 - Why do we need a constructor in a servlet, if we use the init() method?
init() method in a servlet is used when any initialization that your servlet needs to have done before handling a request should be done from the init() method. Constructor is used by the container (container uses the constructor to cretae an instance of the servlet). Just like a normal POJO class that might have an init() method, it is no use calling the init() method if you have not constructed an object to call it.
5 - Why is HttpServlet declared abstract?
The HTTPServlet class is abstract because HTTPServlet class service methods do nothing and need to be overridden by subclass. This is an implementation of Servlet interface, which mean you need not to implement all methods.
6 - Can servlet have a constructor ?
Yes, you can have constructors in servlet. you can perform normal operations with the constructor, but cannot call that constructor explicitly by the new keyword. servlet container is responsible for instantiating the servlet.
7 - What is Servlet Container?
Servlet container or web container is the web server component that interacts with servlets. Servlet container load, initialize and execute servlets. The Servlet container is use to dynamically generate the web page on the server side. A container handles large number of requests as it can hold many active servlets, listeners etc.
8 - What's the difference between doGet() and doPost()?
doGet()
doPost()
doGet() method is limited to send 2k of data. It has no limitation to send data and It is possible to
send files and even binary data such as serialized Java
objects
Data is send in header Data is send in request body.
doGet Parameters are not encrypted doPost Parameters are encrypted
It is faster and commonly used. Slower in compare to doGet.
It allow bookmaks. It doesn't allow bookmarks.
doGet() should be idempotent. doPost() does not need to be idempotent.

9 - What's the difference between ServletConfig and ServletContext?
ServletConfig
ServletContext
Use it to pass deploy the Information to Servlet e.g-( A DataBase name or EJB look up name). Use it to access Web-application parameter(it has setAttribute/getAttribute method).
ServletContext also configure in Deployment Descriptor.
Use it access the servletContext Use it as a kind of application bulletin-board,where you can put up messages or
use it to get the server information including the name version of container
ServletConfig sc = this.getServletConfig(); ServletContext sc=this.getServletConfig.getServletContext();
String a=sc.getInitParameter("email"); String a=sc.getInitParameter("Company-email");
One Servlet Config Object per Servlet. One Servlet Context per Web-Application.
Entry in web.xml:-
<servlet>
<servlet-name>LoginServlet</servlet-name>
<sevlet-class>LoginServlet</sevlet-class>
<init-param>
<param-name>email</param-name>
<param-value>abc@yahoo.com</param-value>
</init-param>
</servlet>
			
Entry in web.xml:-
<web-apps>
<context-param>
<param-name>companyemail</param-name>
<param-value>efg@rkgit.com</param-value>
</context-param>
</web-apps>
			
No setAttribute and getAttribute in ServletConfig. ServletContext has setAttribute(String name,Object o)to set value during coding
and getAttribute to reterive the set value.

10 - When declaring a listener in the DD, which sub-element of the element is required.
<listener-class> sub-element of the <listener> element is required.
11 - What is difference between forward and include?
forward
include
Used to forward a request from one servlet to another servlet. This method must be used when the output is completely generated by the secondservlet. If the PrintWriter object is accessed by the first servlet already, then an exception is thrown by this method. This method is used to invoke one servlet from another servlet like the forward() method. However, you can also include the output of the first servlet with the current putput. The first servlet with the current output. The first servlet can make use of the PrintWriter object even after calling the inclide method.
ServletContext sc = this.getServletConfig.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/SecondServlet");
rd.forward(request,response);
ServletContext sc = this.getServletConfig().getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/SecondServlet");
rd.include(request,response);

12 - What is the difference between forward and sendRedirect()?
  • Forward () run on server side and sendRedirectv() run on client as well as on server side.
  • Using sendRedirec()t you can forward request to any other site weather on same or other server but in forward () the request has to be forwarded to same web application.
  • Forward () hold the previous request and response object but sendRedirect () create fresh request and response object.
  • sendRedirect () is slower than forward() as it create new request and response objects.
  • Use forward() when you want to use same data in new resource we can use request.setAttribute () as you have request object available. But in sendRedirect if you want to use we have to store the data in session or pass along with the URL.

13 - What is cookie?
Cookies are small text files that are used by a Web server to keep track of users. A cookie has value in the form of key-value pairs. They are created by the server and sent to the client with the HTTP response headers. A server can send one or more cookies to the client. A web-browser, which is the client software, is expected to support 20 cookies per host and the size of each cookie can be a maximum of 4 bytes each.
14 - How to set cookie and how to delete a cookie?
To set a cookie you need to follow below steps:
  • Create a cookie object - Cookie c= new Cookie("user preference","red");
  • c.setMaxAge(int); method is use to specify the maximum amount of time for which the client browser retains cookie value.
  • HttpServletResponce.addChoice(c); use to send cookie to the client.
To delete a cookie you need to set the setMaxAge(0), a zero value causes the cookie to be deleted.
15 - What is XML?
XML stands for a Extensible Markup Language, it is design to carry data not to display data. There are not predefine tags, you must define your own tag. It is plateform indepentdent.
16 - What is Session?
Session is used to store the conversational state across multiple requests from the same client. Between several request and response server not able to identify which client is getting request. When there is need to maintain the conversational state, session is needed.
17 - What are the different ways to generate session-tracking?
Approaches to Session-Tracking
  • Session API
  • URL - rewriting
  • Cookies
  • Hidden Form Field

18 - How many servlet objects are created if we have 10 servlets in web application?
We need instace for each servlet to access it that why 10 servlet object will be created for first client request.
19 - What is the difference in between encodeRedirectURL and encodeURL?
Both are method of HttpResponse object. Both rewrite the URL to include session data if necessary encodeURL is a normal link on html page. encodeRedirectURL is for a link you're passing to response.sendRedirect().
20 - What is filter in Java?
Filters are Java Components very similar to servlets that you can use to intercept and process requests before they are sent to the servlet, or to process responses after the servlet has completed, but before the response goes back to the client.
The container decides when to invoke your filters based on deceleration in the DD.