0% found this document useful (0 votes)
3 views

java unit 3

The document provides an overview of key concepts in Java Servlet programming, including session management, servlet life cycle, and the Filter API. It explains how to set and retrieve session values, the life cycle stages of a servlet, and the differences between various HTTP methods. Additionally, it discusses the advantages of using filters, the characteristics of the HTTP protocol, and the MVC architecture in web applications.

Uploaded by

heylegend02
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)
3 views

java unit 3

The document provides an overview of key concepts in Java Servlet programming, including session management, servlet life cycle, and the Filter API. It explains how to set and retrieve session values, the life cycle stages of a servlet, and the differences between various HTTP methods. Additionally, it discusses the advantages of using filters, the characteristics of the HTTP protocol, and the MVC architecture in web applications.

Uploaded by

heylegend02
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/ 13

UNIT 3

Q.1 What is a Session? How to set value and get value from session?
> In Java, a session refers to a mechanism for storing and managing data specific to a user or a
conversation between a client and a server. Sessions are commonly used in web development to
store user information, login details, and other temporary data.

In Java, you can use the HttpSession interface to work with sessions. Here's how to set and get values
from a session:

Set value in session:

import javax.servlet.http.HttpSession;

// Get the session object

HttpSession session = request.getSession();

// Set a value in the session

session.setAttribute("username", "johnDoe");

Get value from session:

// Get the session object

HttpSession session = request.getSession();

// Get the value from the session

String username = (String) session.getAttribute("username");

Q.2 Explain Servlet life cycle.


>

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException


5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource for example memory, thread etc. The
syntax of the destroy method of the Servlet interface is given below:

public void destroy()

Q.3 Difference between servlet config and servlet context.

Q.4 What is filter API?


> In Java, the Filter API is a part of the Servlet specification that allows you to perform filtering tasks
on requests and responses in a web application. Filters can modify the request and response objects,
log information, or perform other processing tasks before or after a request is handled by a servlet or
JSP.

Here are some key points about the Filter API in Java:

Filter: A filter is an object that can transform the request or response headers and content before
and after a servlet is executed.

1. *Filter Interface*: The javax.servlet.Filter interface must be implemented to create a filter. This
interface has three main methods:

- init(FilterConfig filterConfig): Called by the web container to initialize the filter.

- doFilter(ServletRequest request, ServletResponse response, FilterChain chain): Performs the


filtering task. It can modify the request and response objects and pass control to the next filter in the
chain or the target resource.

- destroy(): Called by the web container to indicate that the filter is being taken out of service.
2. *Filter Chain*: Filters can be configured in a chain, where each filter can perform its task and pass
the request and response to the next filter in the chain.

3. *Configuration*: Filters are configured in the web.xml deployment descriptor or using


annotations. The configuration specifies which URLs the filter should be applied to.

4. *Common Uses*: Filters are commonly used for tasks such as:

- Authentication and authorization checks

- Logging and auditing

- Data compression

- Input validation and sanitization

- Transforming response content

Q.5 Explain advantages of Filter API?


> Some of the advantages of using Filter API are:

1. Reusability: Filters can be used to apply a specific behavior to multiple servlets or JSPs without
duplicating code. This makes it easier to maintain and update the application.

2. Modularity: Filters are independent components that can be added or removed from an
application without affecting the application's core functionality. This provides developers with the
flexibility to add or remove features as required.

3. Centralized control: Filters provide a centralized point of control for common tasks such as
authentication, logging, and caching. This makes it easier to manage and maintain the application.

4. Improved performance: Filters can be used to cache responses, compress data, or perform other
optimizations that can improve the performance of the application.

5. Security: Filters can be used to enforce security policies such as authentication, authorization, and
encryption. This helps to ensure that sensitive data is protected from unauthorized access.

Q.6 What is the difference between doGet() and doPost() methods in Servlets?
Q.7 Discuss the use of GET and POST with example.
>GET:

- Used for retrieving data from a server

- Data is sent in the URL as query parameters

- Limited to a small amount of data (around 2000 characters)

- Can be cached by the browser and server

- Can be bookmarked

Example:

- Request: GET /users?name=John&age=30

- Server responds with a list of users matching the name and age

POST:

- Used for creating or updating data on the server

- Data is sent in the request body

- No limit on the amount of data that can be sent

- Not cached by the browser or server

- Cannot be bookmarked
Q.8 What is Filter? List the applications of filter.
> Filter:

A filter is an object that can transform the request or response headers and content before and after
a servlet is executed.

Q.9 Explain Request and Response object in Servlet


>HttpServletRequest (Request Object)

- Methods:

- getParameter(String name): Returns the value of a request parameter.

- getParameterNames(): Returns an enumeration of parameter names.

- getParameterValues(String name): Returns an array of values for a parameter.

- getHeaders(String name): Returns the value of a request header.

- getHeaderNames(): Returns an enumeration of header names.

- getMethod(): Returns the HTTP method (GET, POST, PUT, etc.).

- getRequestURI(): Returns the requested URI.

- getContextPath(): Returns the context path.

- getServletPath(): Returns the servlet path.

- getQueryString(): Returns the query string.

- getReader(): Returns a reader for the request body.

- getInputStream(): Returns an input stream for the request body.

- Attributes:

- setAttribute(String name, Object value): Sets a request attribute.

- getAttribute(String name): Returns a request attribute.

- removeAttribute(String name): Removes a request attribute.

- HttpServletResponse (Response Object)

- Methods:

- setStatusCode(int code): Sets the HTTP status code.

- setHeader(String name, String value): Sets a response header.

- addHeader(String name, String value): Adds a response header.


- getWriter(): Returns a writer for the response body.

- getOutputStream(): Returns an output stream for the response body.

- sendRedirect(String url): Redirects the client to a new URL.

- containsHeader(String name): Checks if a header is already set.

- Attributes:

- setAttribute(String name, Object value): Sets a response attribute.

- getAttribute(String name): Returns a response attribute.

- removeAttribute(String name): Removes a response attribute.

These objects provide a way for servlets to interact with the client's request and generate a
response. The request object contains information about the client's request, such as parameters,
headers, and body data. The response object allows the servlet to set the status code, headers, and
body data for the response.

Q.10 Write a Java Servlet to demonstrate the use of Session Management


>

Q.11 Write servlet which displayed following information of client:


I. Client Browser

II. Client IP address

III. Client Port No

IV.Server Port No

V.Local Port No

VI. Method used by client for form submission

VII. Query String name and values

>

Q.12 Write line(s) of code in JSP for following. I. Session read and write
II. URL rewriting sending and retrieving parameter(s)

III. URL redirection

IV.Print “hello world” as output

V.Include the other JSP file statically


VI. Expression to display date as output

VII. Method of setting the JSP parameters to use in JSTL

>

Q.13 What is doFilter() method? What are its parameters? Give its use with proper
Example.

> The doFilter() method is a part of the Filter interface in Java Servlet programming. It is used to
perform filtering tasks, such as authentication, logging, or data compression, on requests and
responses.

The doFilter() method has the following parameters:

- ServletRequest request: the request object

- ServletResponse response: the response object

- FilterChain chain: the filter chain object

Q.14 List out different types of servlet event and explain it.
> 1. ServletRequestEvent:

- Fired when a request is received by the servlet container.

- Provides access to the request object and the servlet context.

- Can be used to perform tasks such as logging, authentication, and resource allocation.

2. ServletRequestAttributeEvent:

- Fired when an attribute is added, removed, or replaced in a request.

- Provides access to the attribute name, value, and the request object.

- Can be used to track changes to request attributes.

3. ServletContextEvent:

- Fired when the servlet context is initialized or destroyed.

- Provides access to the servlet context and the servlet container.

- Can be used to perform tasks such as initializing or destroying resources, and registering or
unregistering servlets and filters.

4. ServletContextAttributeEvent:

- Fired when an attribute is added, removed, or replaced in the servlet context.


- Provides access to the attribute name, value, and the servlet context.

- Can be used to track changes to context attributes.

5. HttpSessionEvent:

- Fired when a session is created, destroyed, or timed out.

- Provides access to the session object and the servlet context.

- Can be used to perform tasks such as session management, authentication, and resource
allocation.

6. HttpSessionAttributeEvent:

- Fired when an attribute is added, removed, or replaced in a session.

- Provides access to the attribute name, value, and the session object.

- Can be used to track changes to session attributes.

7. ServletContainerInitializerEvent:

- Fired when a servlet container is initialized or destroyed.

- Provides access to the servlet container and the servlet context.

- Can be used to perform tasks such as registering or unregistering servlets and filters, and
initializing or destroying resources.

Q.15 What is servlet filters? Give the necessary API for filters and explain their use.
>

Q.16 Develop any Servlet application which demonstrates use of session


management.
>

Q.17 Give the characteristics of the HTTP protocol and explain the GET, HEADand PUT
methods of the HTTP protocol.
> Characteristics of HTTP Protocol:

1. Request-Response Protocol: HTTP is a request-response protocol, where a client sends a request to


a server, and the server responds with the requested resources.

2. Stateless: HTTP is a stateless protocol, meaning that each request is independent of the previous
requests.
3. Connectionless: HTTP is a connectionless protocol, meaning that a new connection is established
for each request.

4. Text-Based: HTTP is a text-based protocol, using human-readable messages to communicate


between client and server.

5. Platform-Independent: HTTP is platform-independent, allowing communication between different


devices and operating systems.

HTTP Methods:

GET:

- Purpose: Retrieve a resource from the server.

- Request Body: No request body is sent.

- Response: The server returns the requested resource in the response body.

- Cacheable: Yes, GET responses are cacheable.

HEAD:

- Purpose: Retrieve metadata about a resource without fetching the resource itself.

- Request Body: No request body is sent.

- Response: The server returns only the HTTP headers, without the response body.

- Cacheable: Yes, HEAD responses are cacheable.

PUT:

- Purpose: Create or update a resource on the server.

- Request Body: The request body contains the resource data to be created or updated.

- Response: The server returns a success message or an error message.

- Idempotent: Yes, PUT is an idempotent method, meaning that making the same request multiple
times has the same effect as making it once.

These three methods are commonly used in HTTP communication, and understanding their purposes
and characteristics is essential for building web applications and services.

Q.18 Explain MVC architecture in detail


> The model designs based on the MVC architecture follow MVC design pattern. The application logic
is separated from the user interface while designing the software using model designs.

The MVC pattern architecture consists of three layers:

Model: It represents the business layer of application. It is an object to carry the data that can also
contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data that the
model contains.

Controller: It works on both the model and view. It is used to manage the flow of application, i.e.
data flow in the model object and to update the view whenever data is changed.

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Model Layer

The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and store the
model state in the database. Using the model layer, rules are applied to the data that represents the
concepts of application.

View Layer

As the name depicts, view represents the visualization of data received from the model. The view
layer consists of output of application or user interface. It sends the requested data to the client, that
is fetched from model layer by controller.

Controller Layer

The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then sent to
model for data processing. Once they are processed, the data is sent back to the controller and then
displayed on the view.
Q.19 What is Request Dispatcher? What is the difference between Request dispatcher’s
forward() and include() method?
> The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content of
another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet,
JSP file, or HTML file) on the server.

public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML
file) in the response.

As you see in the above figure, response of second servlet is sent to the client. Response of the first
servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the first
servlet that is being sent to the client.

You might also like