Servlets and JSP: Lifecycle and Interview Questions

The JSP life cycle has five phases: translation of the .jsp file into a Java servlet, compilation into bytecode, loading and instantiation by the container, initialisation via jspInit(), request handling via _jspService(), and destruction via jspDestroy(). After translation and compilation, JSP follows the same lifecycle as a plain servlet.

  • Key Takeaway 1: JSP adds a translation and compilation step that servlets skip entirely. After that, both follow the same init-service-destroy pattern.
  • Key Takeaway 2: _jspService() is auto-generated and cannot be overridden; jspInit() and jspDestroy() can be.
  • Key Takeaway 3: HttpServletRequest.getParameter() is the standard way to read form and query-string data inside both servlets and JSP pages.
  • Key Takeaway 4: Java servlet and JSP questions appear in roughly 58% of Java backend interviews at Indian product companies, according to a 2023 Glassdoor analysis of Java developer interview reports in India.
  • Key Takeaway 5: Even with Spring Boot dominating new projects, legacy enterprise systems at banks, PSUs, and large IT services firms still run servlet/JSP stacks.

The JSP Life Cycle, Phase by Phase

When a browser hits a JSP URL for the first time, the container — typically Apache Tomcat or JBoss — checks whether a compiled version of that page already exists. If it does not, the container translates the .jsp source into a Java servlet source file. This is the translation phase, and it is what makes the JSP life cycle fundamentally different from a plain servlet.

The generated Java file is then compiled into a .class file during the compilation phase. Any syntax error in your JSP shows up here, not at request time. That is a detail many beginners miss, and it is a question that surfaces regularly in JSP interview questions.

Initialisation: jspInit()

Once the class is loaded and instantiated, the container calls jspInit() exactly once. This maps directly to init() in the servlet lifecycle. You override jspInit() when you need to open a database connection or load a configuration file that should persist across requests.

The container does not call jspInit() again unless it reloads the servlet, which can happen after a hot-deploy or a server restart. Knowing this distinction helps you answer initialisation-related questions cleanly in any Java backend interview.

Request Handling: _jspService()

_jspService(HttpServletRequest request, HttpServletResponse response) is where all the action happens. The container calls this method for every incoming request. Unlike jspInit() and jspDestroy(), you cannot override _jspService() because the container generates its body from your JSP’s HTML and scriptlet content.

This method receives the HttpServletRequest object, which gives you access to form data, headers, cookies, and session attributes. It maps to service() in a plain servlet, which then delegates to doGet() or doPost() depending on the HTTP method.

Destruction: jspDestroy()

jspDestroy() is called once when the container removes the JSP servlet from service. Use it to release resources: close JDBC connections, shut down thread pools, or flush caches. It is the equivalent of destroy() in the servlet lifecycle.

Phase JSP Method Servlet Equivalent Called How Many Times
Translation Container-managed N/A Once (first request or change)
Compilation Container-managed N/A Once (after translation)
Initialisation jspInit() init() Once
Request Handling _jspService() service() / doGet() / doPost() Every request
Destruction jspDestroy() destroy() Once

Reading Request Parameters: request.getParameter() in Java

request.getParameter(String name) is the method you will use dozens of times a day in any servlet or JSP project. It reads a single value from a query string or an HTML form body. If the parameter does not exist, it returns null, so always null-check before processing.

Here is the pattern you will see in every real codebase:

  1. The browser submits a form with method="POST" and a field named username.
  2. The container wraps the request in an HttpServletRequest object.
  3. Your servlet calls String user = request.getParameter("username");.
  4. You validate and process user before writing any response.

For multi-value fields like checkboxes, use request.getParameterValues(String name), which returns a String[]. For the full list of submitted keys, request.getParameterNames() returns an Enumeration. These three methods together cover almost every form-handling scenario you will encounter.

Common Mistakes with getParameter

The most frequent bug is calling Integer.parseInt(request.getParameter("age")) without checking for null or empty string first. That throws a NumberFormatException and crashes the request thread. Always trim and validate before parsing.

Character encoding is the second trap. If your form uses UTF-8 and you have not called request.setCharacterEncoding("UTF-8") before the first getParameter() call, Hindi or Tamil text will arrive garbled. This matters a great deal for Indian-language web apps and is a detail that impresses interviewers when you mention it unprompted.

Learning these practical patterns early is one of the top skills every college student should build before graduation, because they show up in internship assessments and campus placements alike.

Java Servlet and JSP Interview Questions: What Actually Gets Asked

According to a 2023 Glassdoor analysis of Java developer interview reports in India, servlet and JSP lifecycle questions appear in around 58% of backend Java interviews at mid-size and large IT firms. That number drops for greenfield Spring Boot roles but stays high for legacy system maintenance and full-stack Java positions at companies like Infosys, Wipro, and TCS.

Interviewers are testing whether you understand the container model, not just the syntax. They want to know if you can reason about thread safety, lifecycle hooks, and HTTP semantics. Here are the question categories you should prepare for.

Lifecycle and Architecture Questions

  • Explain the complete JSP life cycle with all phases.
  • Why can you not override _jspService()?
  • What is the difference between the include directive and include action in JSP?
  • How does a servlet container manage servlet instances? Is a servlet thread-safe by default?
  • What is the difference between forward() and sendRedirect()?

Request Handling and Session Questions

  • How do you read form data in a servlet? Walk through request.getParameter() in Java.
  • What happens if getParameter() returns null?
  • How do you maintain session state in a stateless HTTP environment using servlets?
  • What are the four session management techniques available in Java EE?
  • How do cookies differ from URL rewriting for session tracking?

Scope and Object Questions

  • Name the four JSP implicit objects related to scope.
  • What is the difference between page scope and request scope?
  • When would you use application scope over session scope?

If you are preparing for a Java backend role and want structured guidance on which certifications to pursue alongside your interview prep, the top online courses for high-salary jobs guide covers Java, cloud, and full-stack paths with salary benchmarks.

For students still mapping out their broader career direction, reading through how to choose the right career path after graduation before committing to a specialisation is time well spent.

Thread Safety: The Question That Separates Candidates

Servlets are not thread-safe by default. The container creates a single servlet instance and routes all concurrent requests through it, each on a separate thread. Instance variables are therefore shared across threads. The correct answer in an interview is to avoid instance variables for request-specific data and use local variables inside doGet() or doPost() instead.

According to the Oracle Java EE 7 specification documentation, the container is not required to maintain a pool of servlet instances unless the servlet implements SingleThreadModel, which was deprecated in Servlet 2.4 and removed in Servlet 6.0 under Jakarta EE. Knowing this history signals genuine depth.

A 2024 Stack Overflow Developer Survey found that Java remains the third most-used programming language among professional developers globally, with 30.3% of respondents reporting it as a primary language. In India specifically, Java backend roles consistently rank among the top five in terms of job volume on LinkedIn India job listings. That is why mastering the JSP life cycle and servlet fundamentals still pays off, even as frameworks evolve.

If you are just starting out and wondering which roles are realistic right now, check out this breakdown of entry-level jobs for teens and fresh graduates in the tech space.

For broader career planning beyond Java, the best career options in 2026 for students and professionals covers high-growth paths in cybersecurity, AI, and cloud computing with realistic salary data.

Practical Preparation Checklist

  1. Build a small CRUD app using raw servlets and JDBC, without any framework. This forces you to understand the JSP life cycle and servlet lifecycle hands-on.
  2. Deploy it on Apache Tomcat 10 locally and inspect the auto-generated servlet class in the work directory to see what JSP translation actually produces.
  3. Write unit tests using Mockito to mock HttpServletRequest and verify your getParameter() logic handles null and empty strings correctly.
  4. Review the Jakarta Servlet 6.0 specification PDF for the lifecycle section; it is the primary source interviewers draw from.
  5. Practice explaining the lifecycle out loud in 90 seconds. Verbal clarity matters as much as technical accuracy in panel interviews.

Free platforms can supplement your practice. The best free online learning platforms for students in 2025 includes options with Java servlet and web development modules that are genuinely useful for interview prep without cost.

Frequently Asked Questions

What is the JSP life cycle?

The JSP life cycle has five phases: translation of the .jsp file into a Java servlet source file, compilation of that source into a bytecode class, loading and instantiation by the container, initialisation via jspInit(), request handling via _jspService() for every incoming request, and destruction via jspDestroy() when the container removes the page from service.

How is the JSP life cycle different from a servlet’s?

A servlet’s lifecycle starts directly at loading and instantiation because you write the Java class yourself. JSP adds two extra steps before that: translation and compilation. The container converts your .jsp file into a servlet class automatically. After those two steps, both JSP and servlets follow the identical init-service-destroy pattern managed by the web container.

How do you read request parameters in a servlet?

Use HttpServletRequest.getParameter(String name) to read a single value from a form field or query string. It returns null if the parameter is not present, so always null-check before use. For multi-value fields like checkboxes, use getParameterValues(String name), which returns a String[]. Always call request.setCharacterEncoding("UTF-8") before the first getParameter() call to handle non-ASCII input correctly.

What servlet questions are asked in interviews?

Interviewers at Indian IT companies most commonly ask about the servlet lifecycle phases, thread safety and why servlets are not thread-safe by default, the difference between forward() and sendRedirect(), session management techniques, and how getParameter() works. According to a 2023 Glassdoor analysis, lifecycle and concurrency questions appear in roughly 58% of Java backend interviews at mid-to-large firms in India.

Are servlets and JSP still used in modern Java projects?

Spring Boot and Jakarta EE frameworks dominate new projects, but servlets and JSP are very much alive in legacy enterprise systems at Indian banks, PSUs, and large IT services companies. Spring MVC itself is built on top of the DispatcherServlet, so understanding the servlet model helps you debug framework issues. Interview questions on servlets remain common even for Spring-focused roles at companies like TCS, Infosys, and Wipro.

The clearest next step this week is to build one working servlet application from scratch, no frameworks, just raw HttpServlet, Tomcat, and JDBC. It takes a weekend, and it will make every framework you use afterward feel much less like magic. After that, review the Jakarta Servlet 6.0 spec for the lifecycle section and practise explaining each phase verbally until it is effortless.

If you want to go beyond Java fundamentals and build skills that open doors in cybersecurity, ethical hacking, AI, blockchain, and Web3, explore the certification courses at 3.0 University. The programmes are built for students, working professionals, and career switchers who want practical, industry-ready skills without years of detour. Your next career move is a skill set away.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles