Servlet Interview Questions and Answers
Question - 21 : - Why don't we write a constructor in a servlet?
Answer - 21 : - Container writes a no argument constructor for our servlet.
Question - 22 : - When we don't write any constructor for the servlet, how does container create an instance of servlet?
Answer - 22 : - Container creates instance of servlet by calling Class.forName(className).newInstance().
Question - 23 : - Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?
Answer - 23 : - Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.
Question - 24 : - What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?
Answer - 24 : - We can give relative URL when we use ServletRequest and not while using ServletContext.
Question - 25 : - Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?
Answer - 25 : - Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.
Question - 26 : - What is a Servlet?
Answer - 26 : - A Servlet is a Java program that runs on a Web server. It is similar to an applet but is processed on the server rather than a client’s machine. Servlets are often run when the user clicks a link, submits a form, or performs another type of action on a website
Question - 27 : - What is a Cookie?
Answer - 27 : - A cookie is a piece of information that is present between multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
Question - 28 : - How PrintWriter is different from ServletOutputStream?
Answer - 28 : - PrintWriter is basically a character-stream class. On the other hand, ServletOutputStream is a byte-stream class. The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information.
Question - 29 : - Explain is servlet mapping?
Answer - 29 : - Servlet mapping is a process of defining an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.
Question - 30 : - What are the annotations used in Servlet 3?
Answer - 30 : -
The important 3 annotations used in the servlets are.
- @WebServlet : for servlet class.
- @WebListener : for listener class.
- @WebFilter : for filter class.