0% found this document useful (0 votes)
7 views11 pages

MOD4 Ajava Both Model Paper Answers Removed

Uploaded by

muttu1757
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

MOD4 Ajava Both Model Paper Answers Removed

Uploaded by

muttu1757
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Module 4

21CS642 Solved Model Question Paper-1

7.A] List and explain core classes and interfaces in the javax.servlet package.
Answer:
INTERFACES CLASSES

Servlet ServletInputStream

ServletContext ServletOutputStream

ServletConfig ServletException

ServletRequest UnavailableException

ServletResponse GenericServlet

Interface Summary

Servlet Defines methods that all servlets must implement.

ServletRequest Defines an object to provide client request information to a servlet.

ServletResponse Defines an object to assist a servlet in sending a response to the client.

A servlet configuration object used by a servlet container to pass information to a


ServletConfig
servlet during initialization.

Defines a set of methods that a servlet uses to communicate with its servlet
ServletContext container, for example, to get the MIME type of a file, dispatch requests, or write to a
log file.

Class Summary

GenericServlet Defines a generic, protocol-independent servlet.

Provides an input stream for reading binary data from a client request,
ServletInputStream
including an efficient readLine method for reading data one line at a time.

ServletOutputStream Provides an output stream for sending binary data to the client.

ServletException Defines a general exception a servlet can throw when it encounters difficulty.

Amruth Patil, Dept of CSE, DSATM


Defines an exception that a servlet or filter throws to indicate that it is
UnavailableException
permanently or temporarily unavailable.

Core Interfaces in javax.servlet


1. Servlet Interface
• Purpose: The fundamental interface that all servlets must implement. It provides the methods
required for servlet lifecycle management and request handling.
• Key Methods:
• void init(ServletConfig config): Initializes the servlet with configuration parameters.
• void service(ServletRequest request, ServletResponse response): Handles requests and generates
responses.
• void destroy(): Cleans up resources before the servlet is destroyed.
• ServletConfig getServletConfig(): Returns the servlet configuration.
• String getServletInfo(): Provides information about the servlet.
2. ServletRequest Interface
• Purpose: Provides methods to obtain request data and metadata from the client request.
• Key Methods:
• Object getAttribute(String name): Retrieves an attribute from the request.
• Enumeration<String> getAttributeNames(): Returns an enumeration of attribute names.
• String getParameter(String name): Retrieves a parameter from the request.
• Enumeration<String> getParameterNames(): Returns an enumeration of parameter names.
• BufferedReader getReader(): Retrieves the request body as a BufferedReader.
3. ServletResponse Interface
• Purpose: Defines methods for sending responses to the client.
• Key Methods:
• void setContentType(String type): Sets the MIME type of the response.
• PrintWriter getWriter(): Retrieves a PrintWriter to write response data.
• void setCharacterEncoding(String charset): Sets the character encoding for the response.
• void setContentLength(int len): Sets the length of the response content.
4. ServletConfig Interface
• Purpose: Provides configuration information to a servlet, such as initialization parameters.
• Key Methods:
• String getInitParameter(String name): Retrieves an initialization parameter.
• Enumeration<String> getInitParameterNames(): Returns an enumeration of initialization
parameter names.
• ServletContext getServletContext(): Returns the servlet context.
5. ServletContext Interface
• Purpose: Provides a servlet with information about its environment and allows interaction with
other servlets and web resources.
• Key Methods:
• String getContextPath(): Returns the context path of the web application.
• RequestDispatcher getRequestDispatcher(String path): Returns a RequestDispatcher for a given
path.
• InputStream getResourceAsStream(String path): Retrieves a resource as an InputStream.
• void log(String msg): Writes a log message.

Amruth Patil, Dept of CSE, DSATM


6. RequestDispatcher Interface
• Purpose: Allows forwarding a request to another resource or including the content of another
resource in the response.
• Key Methods:
• void forward(ServletRequest request, ServletResponse response): Forwards the request to another
resource.
• void include(ServletRequest request, ServletResponse response): Includes the content of another
resource in the response.
Core Classes in javax.servlet
1. GenericServlet Class
• Purpose: Provides default implementations for the Servlet interface methods. It simplifies the
development of servlets by handling common functionality.
• Key Methods:
• void service(ServletRequest req, ServletResponse res): Must be overridden by subclasses to
handle requests.
• ServletConfig getServletConfig(): Returns the servlet configuration.
2. HttpServlet Class
• Purpose: Extends GenericServlet and provides additional methods specific to HTTP requests, such
as handling GET, POST, PUT, and DELETE requests.
• Key Methods:
• void doGet(HttpServletRequest req, HttpServletResponse resp): Handles GET requests.
• void doPost(HttpServletRequest req, HttpServletResponse resp): Handles POST requests.
• void doPut(HttpServletRequest req, HttpServletResponse resp): Handles PUT requests.
• void doDelete(HttpServletRequest req, HttpServletResponse resp): Handles DELETE requests.
3. ServletInputStream Class
• Purpose: Provides an input stream for reading binary data from the client request, useful for
processing binary data like files.
• Key Methods:
• int read(): Reads the next byte of data.
• int read(byte[] b): Reads bytes into an array.
• int read(byte[] b, int off, int len): Reads bytes into an array from a specified offset and length.
4. ServletOutputStream Class
• Purpose: Provides an output stream for sending binary data to the client, such as images or
files.
• Key Methods:
• void write(int b): Writes a byte of data.
• void write(byte[] b): Writes an array of bytes.
• void write(byte[] b, int off, int len): Writes a portion of an array of bytes.
5. ServletException Class
• Purpose: Indicates a servlet-specific problem or error during request processing.
• Key Methods:
• Throwable getRootCause(): Returns the root cause of the exception.
• String getMessage(): Returns a detailed message about the exception.

Amruth Patil, Dept of CSE, DSATM


6. UnavailableException Class
• Purpose: Signals that a servlet is temporarily unavailable and cannot handle requests at the
moment.
• Key Methods:
• int getUnavailableSeconds(): Returns the number of seconds the servlet will be unavailable.
• String getMessage(): Returns a detailed message about the exception.
Summary
• Interfaces:
• Servlet: Base interface for all servlets.
• ServletRequest: Provides methods for request data.
• ServletResponse: Defines methods for sending responses.
• ServletConfig: Provides servlet configuration information.
• ServletContext: Provides context information and resource interaction.
• RequestDispatcher: Manages request forwarding and inclusion.
• Classes:
• GenericServlet: Convenience class for basic servlet functionality.
• HttpServlet: Handles HTTP-specific requests.
• ServletInputStream: Reads binary data from requests.
• ServletOutputStream: Sends binary data in responses.
• ServletException: Signals servlet errors.
• UnavailableException: Indicates temporary servlet unavailability.

7.B] Explain how to read servlet parameters with an example


Answer:
Note: if difficult to understand, Reading Form Parameters is enough
In a servlet, parameters are often sent from the client (e.g., via an HTML form) and can be
accessed using the HttpServletRequest object. Parameters can be accessed in a variety of ways,
depending on whether they are query parameters, form parameters, or parameters from a URL.

Here’s a breakdown of how to read servlet parameters:


1. Query Parameters
• Purpose: Parameters included in the URL after the ? (query string). Example
URL: http://example.com/servlet?param1=value1&param2=value2.
• Method to Use: getParameter(String name)
• Example Code:
import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

public class QueryParamServlet extends HttpServlet {

@Override

Amruth Patil, Dept of CSE, DSATM


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {

// Retrieve query parameters

String param1 = req.getParameter("param1");

String param2 = req.getParameter("param2");

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

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

out.println("<h1>Query Parameters</h1>");

out.println("<p>param1: " + param1 + "</p>");

out.println("<p>param2: " + param2 + "</p>");

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

2. Form Parameters
• Purpose: Parameters sent via an HTML form using either the GET or POST method.
• Method to Use: getParameter(String name)
• Example HTML Form:
<form action="formServlet" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name">

<label for="age">Age:</label>

<input type="text" id="age" name="age">

<input type="submit" value="Submit">

</form>

• Example Servlet Code:


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

public class FormParamServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,


IOException {

Amruth Patil, Dept of CSE, DSATM


// Retrieve form parameters

String name = req.getParameter("name");

String age = req.getParameter("age");

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

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

out.println("<h1>Form Parameters</h1>");

out.println("<p>Name: " + name + "</p>");

out.println("<p>Age: " + age + "</p>");

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

3. URL Path Parameters


• Purpose: Parameters included in the URL path, typically used with URL rewriting or RESTful web
services.
• Method to Use: getPathInfo(), getServletPath()
• Example URL: http://example.com/servlet/path/to/resource
• Example Servlet Code:
import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

public class PathParamServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,


IOException {

// Retrieve path info

String pathInfo = req.getPathInfo();

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

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

out.println("<h1>Path Parameters</h1>");

out.println("<p>Path Info: " + pathInfo + "</p>");

Amruth Patil, Dept of CSE, DSATM


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

Summary
1. Query Parameters:
• Accessed using req.getParameter("paramName").
• Sent as part of the URL after the ?.
2. Form Parameters:
• Accessed using req.getParameter("paramName").
• Sent via an HTML form with method="post" or method="get".
3. URL Path Parameters:
• Accessed using req.getPathInfo() or req.getServletPath().
• Included in the URL path, often used in RESTful services.

8.A] Explain how to handle HTTP request and response with an example
Answer:
In Java servlets, handling HTTP requests and responses involves overriding methods from
the HttpServlet class. The most common methods are doGet() and doPost(), which correspond to
HTTP GET and POST requests, respectively. Here’s a breakdown of how to handle these
requests and responses with examples.
Common HTTP Methods
1. GET Method
• Purpose: Retrieves data from the server.
• Usage: Often used for requesting data or resources.
• Characteristics: Parameters are sent in the URL.
• Example URL: http://example.com/servlet?param1=value1&param2=value2
2. POST Method
• Purpose: Submits data to be processed by the server.
• Usage: Often used for form submissions and data modifications.
• Characteristics: Parameters are sent in the body of the request, not in the URL.
Example: Handling HTTP Requests and Responses
1. HTML Form for GET and POST Requests
<!DOCTYPE html>

<html>

<head>

<title>Form Example</title>

</head>

<body>

<!-- Form to handle GET requests -->

Amruth Patil, Dept of CSE, DSATM


<h2>GET Request</h2>

<form method="get" action="getServlet">

Name: <input type="text" name="name">

<input type="submit" value="Submit">

</form>

<!-- Form to handle POST requests -->

<h2>POST Request</h2>

<form method="post" action="postServlet">

Name: <input type="text" name="name">

<input type="submit" value="Submit">

</form>

</body>

</html>

2. Handling GET Requests in a Servlet


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

import java.io.PrintWriter;

public class GetServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set content type

response.setContentType("text/html");

// Get the PrintWriter to write the response

PrintWriter out = response.getWriter();

// Retrieve parameters from the request

String name = request.getParameter("name");

// Generate response

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

out.println("<h2>GET Request</h2>");

out.println("<p>Hello, " + name + "!</p>");

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

Amruth Patil, Dept of CSE, DSATM


// Close the PrintWriter

out.close();

3. Handling POST Requests in a Servlet


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

import java.io.PrintWriter;

public class PostServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set content type

response.setContentType("text/html");

// Get the PrintWriter to write the response

PrintWriter out = response.getWriter();

// Retrieve parameters from the request

String name = request.getParameter("name");

// Generate response

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

out.println("<h2>POST Request</h2>");

out.println("<p>Hello, " + name + "!</p>");

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

// Close the PrintWriter

out.close();

Explanation
1. HTML Form:
• GET Form: Submits data using the GET method, appending parameters to the URL.
• POST Form: Submits data using the POST method, including parameters in the request body.
2. Servlets:

Amruth Patil, Dept of CSE, DSATM


• doGet() Method: Handles GET requests. Retrieves parameters from the URL and generates a
response.
• doPost() Method: Handles POST requests. Retrieves parameters from the request body and
generates a response.
Differences Between GET and POST Requests:
Feature GET Request POST Request

Data is included in the request


Data Data is visible in the URL query string. Suitable
body. Suitable for sensitive data
Visibility for non-sensitive data.
and larger amounts of data.

Limited by URL length restrictions (typically


Data Length No practical limits on data size.
around 2048 characters).

Idempotent; multiple identical GET requests Not necessarily idempotent; each


Idempotency
should have the same effect as a single request. request can have a different effect.

Requests can be cached by browsers and


Caching Requests are generally not cached.
servers.

8.B] Write a note on:


i) Session Tracking
ii) Cookies
Answer:
i) Session Tracking
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an user. It is also known as session management in
servlet.
• Http protocol is a stateless so we need to maintain state using session tracking techniques.
• Each time user requests to the server, server treats the request as the new request.
• So we need to maintain the state of an user to recognize to particular user.
There are 2 techniques used in Session tracking:
• Cookies
• HttpSession

ii) Cookies
A cookie is a small piece of information that is persisted between the multiple client requests.
By default, each request is considered as a new request.
In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of
the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.

Amruth Patil, Dept of CSE, DSATM


Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Additional Expected Question below:

Example Demonstrating Usage of Cookies


Here is a complete example of how to use cookies to store and retrieve user information across different
servlets:
1. HTML Form (index.html)
<form method="post" action="MyServlet">

Name: <input type="text" name="user" /><br/>

Password: <input type="password" name="pass" /><br/>

<input type="submit" value="Submit" />

</form>
Amruth Patil, Dept of CSE, DSATM

You might also like