Top 50 Servlet and Filter Interview Questions Answers for Java/JEE developers

Hello Java web developers, if you are preparing for Java Developer interviews and want to prepare Servlet, one of the cores of Java web technology and the backbone of many popular MVC frameworks in the Java world like Spring and Struts then you have come to the right place. Earlier, I have shared free Servlet and JSP courses and in this article, we'll discuss some of the frequently asked, simple, and difficult Servlet interview questions from telephonic interviews of Java web development roles. The list includes frequently asked Servlet questions on key concepts like Servlet life cycle, how Servlet works in Tomcat or a web container, Servlet 3 annotations, Filters, Listeners, and how to customize initialization of Servlet. 

50 Servlet and Filter Interview Questions with Answers

Here is a list of my favorite and popular Java interview questions from Servlet, Filter, Listener, and other key Java web development concepts. Most of these questions are already discussed on my blog and you can find them by doing a quick server. I have also included links wherever I can. 

If you have worked in Servlet and JSP then most likely you will know answers to most of these questions but if you couldn't find answers to any Servlet or Filter questions then drop me a note and I will add the answer. 

1. What is a Servlet?
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. You can create a Servlet by implement javax.servlet.Servlet interface of extending GenericServlet or HttpServlet class.

2. Who cretes instance of Servlet?
The Servlet container is responsible for creating Servlet instances. The servlet container is provided by web servers like Tomcat, Jetty, etc. They also exist in enterprise servers e.g. WebLogic, WebSphere, or Glassfish

3. What is the initialization order of the servlet? when does the Servlet container create an instance of Servlet?
Most of the servlets are initialized at the request time. I mean when a request comes for a Servlet, which is resolved container using URL pattern then it checks if there is any existing instance or not. If there is no instance then the Servlet container creates a new instance of Servlet. That's also the reason that the first request to any Servlet is slower than subsequent ones because most of the time is spent in initializing Sevlet. You can also customize this behavior and initialize the servlet when your application is deployed. This is done by using the load-on-startup tag. 

4. What are Servlet's life-cyle methods?
There are three methods, init() for initialization, service() for processing incoming requests, and destroy() for destroying the servlet instances. These methods are called web containers or servlet contains who are responsible for creating and destroying servlet instances. 

5. Can you declare Constructor inside Servlet? (answer)
Yes, you can declare a constructor inside Servlet in Java, but its, not the correct way to initialize the Servlet because Servlet instances are created by a web server like Tomcat and they call the init() method to initialize the servlet. 

You should put all your initialization logic into the init method as well. You should also make sure to declare a no-argument constructor in Servlet if you define a constructor with a parameter because this is used by Servlet containers like Tomcat or Jetty to create Servlet instances. 

Remember, Java by default adds a no-argument constructor to every class but only when there is no other constructor defined. If you forget to add the default constructor, your Servlet will not be initialized. 

6. What is the difference between the Servlet constructor and the init() method?
The init() method is the right way to initialize a Servlet because this is called by a web container like Tomcat after the servlet instance is created. 

7. What is Servlet Container, What are the responsibilities of Servlet Container?
It's a Java program that follows Servlet specifications. Some examples are Tomcat and Jetty. Their primary responsibility includes creating and destroying Servlet instances and routing requests to SErvlet for processing. 

8. What is the difference between Servlet and Filter?

9. What is the difference between a Filter and a Listener?

10. Difference between RequestDispatcher.forward() and ServletRequest.forward() method? (answer)

11. Difference between Servlet and JSP?
JSP is more HTML than Java while Servlet is more Java than HTML. JSP is also converted to Servlet before execution. JSP was designed for web designers who are more familiar with a markup language like HTML while Servet is for Java developers. In MVC, JSP represent the View part while

12. Difference between GenericServlet and HttpServlet? (answer)
The GenericServlet is used to process any kind of requests but HttpServlet is a specialized implementation to process HTTP requests. Container instead of calling service() method directly call doGet() and doPost() method for GET and POST HTTP requests.  Actually, service method is overridden to forward GET request to doGET() and POST to doPOST etc

13. What are the annotations used in Servlet 3?
There are mainly 3 annotations used for the servlet.
  • @WebServlet : for servlet class.
  • @WebListener : for listener class.
  • @WebFilter : for filter class.

14. What is load-on-startup in servlet? (Answer)

15. Can you pass a negative value to load-on-startup? how does it affect the loading of Servlet

16. How do you get the count of how many times the Servlet was accessed?

Ans: Use Filters and in the doFilter() method, maintain a counter which gets stored in the servletContext.

17. How do you get the number of users who have accessed your application?
Ans: Use HttpSessionListener and increment/decrement the userCount variable which gets stored in the servletContext on the sessionCreated() and sessionDestroyed() method.

18. What is the life cycle of ServletContextListener?

Ans: contextInitialized() and contextDestroyed()

19. What is JSESSIONID in Java? When does JSESSIONID gets created? (answer)

20. Difference between sendredirect and forward in Servlet? (answer)

21. What is the difference between a Web Server and an Application Server?

22. What is the difference between URL Encoding and URL rewriting?

23. What is the difference between ServletContext and ServletConfig in Java?

24. How to control the initialization of Servlet? How will you ensure pre initialization of Servlet?

25. What is the difference between doGET() and doPOST() method?

26. Who calls doGET() and doPOST() method ?

27. Who creates objects of HttpServletRequest and HttpServletResponse?

28. How do you make a Servlet thread-safe?

29. What is the lifecycle of the filter?

30. How do you make your application run using SSL?

31. How do you ensure that a particular servlet can only be accessed after authentication?

32. How to implement authentication and authorization in Servlet application?

33. What is the advantage of Servlet over CGI?
In the case of CGI, a new object is created to process each request which means response time is wasted in object creation, in the case of Servlet, the same object can be re-used to process or handle many requests. This means Servlet is both faster and memory-efficient than CGI. 

Top 50 Servlet and Filter Interview Questions Answers for Java/JEE developers

34. What are major enhancements or features added in Servlet 3.0 API 
Hint - async processing, annotation, modularization of web.xml, etc.

35. What is asynchronous processing in Servlet? Why do you need that?

36. How do you upload a file using Servlet 3.0?

37. What is the ServletContainerInitializer interface? What is the use of it?

38. Why you should not call System.exit() from a Servlet? (answer)

39. What is the life cycle of the Filter?

Ans: init, doFilter, destroy

40. What is the difference between Page and PageContext?
Ans: page and pageContext are implicit variables.

page: page is of class java.lang.Object, and it refers to instances of generated servlet.

Usages of Page:

1) Error bcoz page is Object type

2) <%=((servlet)page).getServletInfo()%> <—-OK:typecast

3) <%=this.getServletInfo()%> <——-OK

pageContext :

pageContext is of type javax.servlet.jsp.PageContext.

pageContext class is an abstract class.

Usages of PageContext:

1) provide convenient methods to get and set attributes in diff scopes.

2) provide convenient methods for transferring requests to other resources in the web application

void include(String relativeURL) & void forward(String relativeURL)

like pageContext.forward(“test.jsp”);

3)store the references to implicit objects

41. How do you ensure that a user session is closed when actually the user has closed the browser window without logging out explicitly?
Ans: In HttpSession, you have a method by the name getLastAccessedTime() which can be used to identify the inactive period and invalidate the session by calling the session.inValidate()

42. How do you upload a file using Servlet? (example)

43. how do you get a ServletContext reference inside a Servlet? (answer)

44. What are different ways of managing sessions in Http Servlet? (answer)

45. What is the difference between idempotent and non-idempotent methods in HTTP? (answer)

46. What is the difference between idempotent and safe methods in HTTP?  (answer)

47. How to get the IP address of the client in the servlet?  (answer)

48. We can use request.getRemoteAddr() to get the client IP address in servlet. (answer)

That's all about some of the frequently asked, simple, and difficult Servlet interview Questions for Java/JEE developers. If you can answer all of these questions with confidence and explain them in a little bit in-depth if required then you are in good shape for attending a job interview for a Java web development position. I have included questions from Servlet fundamentals, Filters, Listeners, HTTP, Session management, Servlet 3.0, and other important topics related to Servlet and JSP.

Thanks for reading this article. If you like these Servlet Interview Questions then please share them with your friends and colleagues. If you have any other questions you want to add to this list then please let me know.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.