Skip to main content

Ultimate Java Servlet Handbook and Top Interview Queries for Professionals

 

Important Servlet Topics

  1. Introduction to Servlets

  2. Servlet Life Cycle

  3. Servlet Configuration

  4. Handling HTTP Requests and Responses

  5. Request Redirect and Forward

  6. Initialization Parameters and Context Parameters

  7. Servlet Filters

  8. Session Management

  9. Handling Cookies

  10. RequestDispatcher

  11. ServletContext

  12. Error Handling in Servlets

1. Introduction to Servlets

Servlets are Java programs that extend the capabilities of a server. They can respond to any type of requests but are commonly used to handle HTTP requests in web applications.

2. Servlet Life Cycle

The life cycle of a servlet is controlled by the servlet container, which follows these steps:

  • Loading and Instantiation: The servlet class is loaded and an instance is created.

  • Initialization: The init() method is called once for initialization.

  • Request Handling: The service() method is called for each request, which then calls doGet(), doPost(), etc.

  • Destruction: The destroy() method is called before the servlet is destroyed.

Example:

public class LifeCycleServlet extends HttpServlet { @Override public void init() throws ServletException { // Initialization code } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle GET request } @Override public void destroy() { // Cleanup code } }

3. Servlet Configuration

Servlets can be configured using annotations or the web.xml file. Configuration includes specifying servlet name, URL patterns, and initialization parameters.

Example (Annotations):

@WebServlet(name = "ExampleServlet", urlPatterns = {"/example"})

public class ExampleServlet extends HttpServlet {

    // Servlet code

}

4. Handling HTTP Requests and Responses

Servlets handle HTTP requests and generate responses using HttpServletRequest and HttpServletResponse objects.

Example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("<html><body>");

    out.println("<h1>Hello, World!</h1>");

    out.println("</body></html>");

}


5. Request Redirect and Forward

  • Redirect: Sends a new request from the client to a different URL.

  • Forward: Forwards the request internally to another resource within the server.

Redirect Example:

java

response.sendRedirect("http://www.example.com");

Forward Example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("<html><body>");

    out.println("<h1>Hello, World!</h1>");

    out.println("</body></html>");

}


6. Initialization Parameters and Context Parameters

  • Initialization Parameters: Specific to a servlet, defined in web.xml or annotations.

  • Context Parameters: Application-wide, defined in web.xml.

Initialization Parameters Example:

xml

<servlet>

    <servlet-name>ExampleServlet</servlet-name>

    <servlet-class>com.example.ExampleServlet</servlet-class>

    <init-param>

        <param-name>param1</param-name>

        <param-value>value1</param-value>

    </init-param>

</servlet>

Context Parameters Example:

xml

<context-param>

    <param-name>contextParam1</param-name>

    <param-value>value1</param-value>

</context-param>


7. Servlet Filters

Filters are used to perform tasks such as logging, authentication, and data compression on request and response objects.

Example Filter:

public class LoggingFilter implements Filter {

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

            throws IOException, ServletException {

        System.out.println("Request received at " + new java.util.Date());

        chain.doFilter(request, response);

        System.out.println("Response sent at " + new java.util.Date());

    }

}

8. Session Management

Sessions are used to maintain state across multiple requests from the same client.

Example:

HttpSession session = request.getSession(); session.setAttribute("username", "JohnDoe");

9. Handling Cookies

Cookies are used to store small pieces of data on the client side.

Example:

Cookie cookie = new Cookie("username", "JohnDoe"); response.addCookie(cookie);

10. RequestDispatcher

RequestDispatcher is used to forward a request from one servlet to another or to include content from another resource.

Forward Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("/newResource"); dispatcher.forward(request, response);

11. ServletContext

ServletContext provides a way to communicate with the servlet container and to get initialization parameters for the whole web application.

Example:

java

ServletContext context = getServletContext(); String param = context.getInitParameter("contextParam1");

12. Error Handling in Servlets

Error handling can be done using try-catch blocks, configuring error pages in web.xml, or by using filters.

Example (web.xml):

xml

<error-page>

    <error-code>404</error-code>

    <location>/error404.jsp</location>

</error-page>

<error-page>

    <exception-type>java.lang.Exception</exception-type>

    <location>/error.jsp</location>

</error-page>


Most Asked Interview Questions for Experienced Java Developers

  1. What is a Servlet?

    • A servlet is a Java class that extends the capabilities of servers hosting applications accessed via a request-response model.

  2. Explain the Servlet life cycle.

    • Loading and Instantiation, Initialization (init method), Request Handling (service method), and Destruction (destroy method).

  3. What are the advantages of using Servlets?

    • Portability, Performance, Integration with Java API, and Ease of development using the Java programming language.

  4. How do you configure a Servlet?

    • By using annotations (@WebServlet) or by configuring in the web.xml file.

  5. What is the difference between doGet and doPost methods?

    • doGet handles GET requests (data sent via URL), while doPost handles POST requests (data sent via the request body).

  6. How can you handle sessions in Servlets?

    • Using HttpSession object, cookies, or URL rewriting.

  7. What is the use of the ServletConfig object?

    • It allows a servlet to access initialization parameters configured in the web application.

  8. How can you handle exceptions in Servlets?

    • By using try-catch blocks, web.xml configuration, or custom error pages.

  9. What are Filters in Servlets?

    • Filters are objects that perform filtering tasks on the request to and response from a servlet.

  10. What is the difference between a Servlet and a JSP?

    • Servlets are Java classes handling business logic, while JSPs are for presentation, embedded with Java code.

  11. How do you forward a request from one servlet to another?

    • Using RequestDispatcher's forward method.

  12. Explain the purpose of the HttpServletResponse object.

    • It provides methods to respond to the client, including sending HTML, setting headers, and setting status codes.

  13. What is the use of the ServletContext object?

    • It provides a view of the web application's environment and allows servlets to share information.

  14. How do you upload a file using a servlet?

    • By handling multipart/form-data requests, typically using libraries like Apache Commons FileUpload.

  15. What is the difference between context attributes and request attributes?

    • Context attributes are shared across the entire application, while request attributes are specific to a single request.

  16. Can you explain the role of annotations in Servlets?

    • Annotations provide a way to configure servlets, filters, and listeners without using web.xml.

  17. What are the security constraints in Servlets?

    • They include authentication, authorization, data confidentiality, and data integrity.

  18. How do you redirect a request to another URL?

    • Using HttpServletResponse's sendRedirect method.

  19. What is the use of the getServletContext method?

    • It retrieves the ServletContext object, allowing interaction with the servlet container.

  20. How do you handle multi-threading in Servlets?

    • Servlets are inherently multi-threaded; proper synchronization and thread safety mechanisms must be used to avoid issues.

These topics and questions cover essential aspects of servlets, providing a solid foundation for understanding and working with Java web applications.

Comments

Popular posts from this blog

Using Java 8 Streams to Find the Second-Highest Salary in an Employee List

To find the second-highest salary from a list of employees using Java 8 streams, you can follow these steps: Create a list of employees with their salaries. Use Java 8 streams to sort the employees by salary in descending order. Skip the first element (which is the employee with the highest salary). Get the first element of the remaining stream (which is the employee with the second-highest salary). Example code: java import java.util.ArrayList; import java.util.List; class Employee { private String name; private double salary; public Employee (String name, double salary) { this .name = name; this .salary = salary; } public double getSalary () { return salary; } } public class SecondHighestSalary { public static void main (String[] args) { List<Employee> employees = new ArrayList <>(); employees.add( new Employee ( "John" , 60000.0 )); employees.add( new Employe...

Top 20 Exception Handling Interview Questions and Answers for Experienced Java Developers

Introduction: Exception handling is a crucial aspect of Java development, ensuring robust and error-tolerant code. Experienced Java developers are expected to have a deep understanding of exception handling mechanisms. In this blog post, we'll explore the top 20 interview questions related to exception handling, accompanied by detailed answers and sample code snippets to help you prepare for your next Java interview. 1. What is an exception in Java? An exception is an event that disrupts the normal flow of a program. In Java, exceptions are objects that represent errors or abnormal situations during runtime. java try { // Code that may throw an exception } catch (ExceptionType e) { // Code to handle the exception } 2. Differentiate between checked and unchecked exceptions. Checked exceptions are checked at compile-time, and the programmer is forced to either catch them or declare that the method throws them. Unchecked exceptions, on the other hand, are not checked at ...

A Deeper Look into the Java 8 Date and Time API with Q&A

  Understanding Java 8 Date and Time API: The Date and Time API introduced in Java 8 is part of the java.time package, providing classes to represent dates, times, durations, and intervals. This new API addresses many issues found in the old java.util.Date and java.util.Calendar classes, such as immutability, thread safety, and improved functionality. Benefits of Java 8 Date and Time API: Immutability : Date and time objects in the java.time package are immutable, making them thread-safe and eliminating issues related to mutability. Clarity and Readability : The API introduces clear and intuitive classes like LocalDate , LocalTime , and LocalDateTime , making code more readable and maintainable. Extensibility : It offers extensibility through the Temporal and TemporalAccessor interfaces, allowing developers to create custom date and time types. Comprehensive Functionality : The API provides comprehensive functionality for date and time manipulation, formatting, parsing, and a...

Subscribe to get new posts

Name

Email *

Message *