6 Web Programming With Servlets And Jsp

Advanced Java Programming · Unit 6

Web Programming with Servlets and JSP

Exam-focused notes for Web Programming with Servlets and JSP (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

Web Programming with Servlets and JSP in short

Servlets and JSP are the Java tools for dynamic web pages. A servlet is Java code that handles web requests. JSP is HTML with Java inside, and it becomes a servlet when it runs.

Web Programming with Servlets and JSP: notes

Servlet architecture and lifecycle

A servlet is a Java class that runs on a web server (a servlet container such as Tomcat) and answers HTTP requests. The browser sends a request, the container passes it to the servlet, and the servlet sends back a response.

The lifecycle has three phases.

  • init(ServletConfig) runs once when the servlet is loaded. It sets up resources.
  • service(request, response) runs for every request. It calls doGet() or doPost().
  • destroy() runs once when the servlet is removed. It frees resources.

The container creates one servlet object and runs each request in its own thread.

Methods of writing servlet programs

There are three ways to write a servlet.

  • Implement the Servlet interface. You must write all five methods.
  • Extend GenericServlet. You write only service(). It is protocol independent.
  • Extend HttpServlet. You override doGet() or doPost(). This is the most common.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        String name = req.getParameter("name");
        out.println("<h1>Hello " + name + "</h1>");
    }
}

The servlet is mapped to a URL with @WebServlet("/hello") or in web.xml.

import javax.servlet.*;
import java.io.*;

public class GenServlet extends GenericServlet {
    public void service(ServletRequest req, ServletResponse res) throws IOException {
        res.getWriter().println("Generic servlet");
    }
}

What this unit covers

  • Servlet architecture and lifecycle
  • Methods of writing servlet programs
  • Differences between JSP and servlets
  • JSP tags and directives
  • Scriptlets and JSP access models
  • JSP implicit objects and their purposes
  • HTML form processing with JSP
  • Servlet APIs
  • Request and response handling

JSP implicit objects and their purposes

2082 · 10 marks

What are the purposes of JSP implicit objects? Describe the methods of writing servlet program with example.[10]

Show solved answer

JSP Implicit Objects and Servlet Programming

Part 1: Purposes of JSP Implicit Objects

JSP implicit objects are pre-defined objects automatically available in JSP pages without explicit declaration. Their main purposes are:

1. Request Handling

  • request object: Captures HTTP request parameters, headers, and cookies sent by the client
  • Purpose: Access form data, query strings, and request metadata

2. Response Management

  • response object: Sends data back to the client
  • Purpose: Set response headers, cookies, and redirect requests

3. Session Management

  • session object: Maintains user-specific data across multiple requests
  • Purpose: Store and retrieve user information during a session

4. Application Scope

  • application object: Shares data across all users and sessions
  • Purpose: Store global application-level information

5. Page Context

  • pageContext object: Provides access to all page-level objects and attributes
  • Purpose: Manage page scope variables and forward/include requests

6. Output Stream

  • out object: Writes content to the response stream
  • Purpose: Display dynamic content to the client

7. Configuration

  • config object: Accesses servlet configuration parameters
  • Purpose: Retrieve initialization parameters

8. Exception Handling

  • exception object: Handles runtime errors (available in error pages)
  • Purpose: Access error information and stack traces

Part 2: Methods of Writing Servlet Programs

Method 1: Extending HttpServlet Class

This is the standard approach where a servlet extends HttpServlet and overrides doGet() and/or doPost() methods.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    
    public void doGet(HttpServletRequest request, 
                      HttpServletResponse response) 
                      throws ServletException, IOException {
        
        // Set response content type
        response.setContentType("text/html");
        
        // Get output stream
        PrintWriter out = response.getWriter();
        
        // Write HTML response
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello from Servlet!</h1>");
        out.println("</body>");
        out.println("</html>");
        
        out.close();
    }
    
    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response) 
                       throws ServletException, IOException {
        doGet(request, response);
    }
}

Method 2: Handling Request Parameters

Servlets can retrieve and process form data submitted by clients.

Example:

public void doPost(HttpServletRequest request, 
                   HttpServletResponse response) 
                   throws ServletException, IOException {
    
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
    // Get parameters from request
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    
    out.println("<html><body>");
    out.println("<h2>User Information</h2>");
    out.println("<p>Name: " + name + "</p>");
    out.println("<p>Email: " + email + "</p>");
    out.println("</body></html>");
    
    out.close();
}

Method 3: Using Session Management

Servlets can maintain user sessions across multiple requests.

Example:

public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) 
                  throws ServletException, IOException {
    
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
    // Get or create session
    HttpSession session = request.getSession();
    
    // Store data in session
    session.setAttribute("username", "john_doe");
    
    // Retrieve data from session
    String user = (String) session.getAttribute("username");
    
    out.println("<html><body>");
    out.println("<p>Welcome: " + user + "</p>");
    out.println("</body></html>");
    
    out.close();
}

Key Points:

  • doGet(): Handles GET requests (URL parameters)
  • doPost(): Handles POST requests (form data)
  • HttpServletRequest: Provides access to request data
  • HttpServletResponse: Used to send response to client
  • PrintWriter: Output stream for writing response content

These methods form the foundation of server-side Java web development and are essential for building dynamic web applications.

Open this answer on its own page →

Servlet APIs

2081 · 10 marks

Discuss about any four servlet APIs. Design a form in JSP to take the necessary information about an employee and when the user click submit button, it will be displayed in second page.[10]

The HttpServletRequest object contains the request sent by the client to the server. Key methods include: - getParameter(String name) - retrieves a single parameter value from the request - getParameterValues(String name) - retrieves multiple values for the same parameter - getMethod() - returns ...

Open this answer on its own page →

Scriptlets and JSP access models

2081 · 5 marks

Define scriptlets. Discuss about JSP access models. [5]

Scriptlets are blocks of Java code embedded directly within JSP (JavaServer Pages) documents. They are enclosed within <% ... % tags and allow developers to write Java logic that executes on the server side during page processing. Syntax: Scriptlets have full access to JSP implicit objects and ca...

Open this answer on its own page →

JSP tags and directives

2080 · 10 marks

What are the various tags used in writing JSP programs? How HTML forms can be processed using JSP? Explain with example.[10]

JSP provides several types of tags for embedding Java code and dynamic content in web pages: Used to declare variables and methods that become part of the servlet class. Contains Java code that executes every time the page is requested. Evaluates a Java expression and outputs the result directly ...

Open this answer on its own page →

Differences between JSP and servlets

0 · 10 marks

How JSP differs from servlets? Discuss various methods of writing servlet programs with suitable example.[10]

Aspect Servlet JSP ---------------------- Type Pure Java program HTML with embedded Java Syntax Java code only Mix of HTML and Java code Development Requires Java programming knowledge Easier for web designers; less Java needed Compilation Compiled to bytecode before deployment Compiled to servle...

Open this answer on its own page →