0% found this document useful (0 votes)
9 views22 pages

Unit 1

The document covers various topics related to Java networking, including the differences between TCP and UDP, RMI applications, JDBC, servlet lifecycle, and the Filter API. It explains concepts such as protocol handlers, URL class usage, session management, and HTTP protocol characteristics. Additionally, it includes code snippets and examples for practical understanding of these concepts.

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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views22 pages

Unit 1

The document covers various topics related to Java networking, including the differences between TCP and UDP, RMI applications, JDBC, servlet lifecycle, and the Filter API. It explains concepts such as protocol handlers, URL class usage, session management, and HTTP protocol characteristics. Additionally, it includes code snippets and examples for practical understanding of these concepts.

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 DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT 1

Q.1 Difference between TCP and UDP.

Q.2 WAP for server client connection using UDP.


> SAME AS Q.1

Q.3 WAP for server client connection using TCP.


>SAME AS Q.1

Q.4 Write an RMI application where client supplies two numbers and server response by
summing it. Provide your custom security policy for this application.
> RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one
system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.

Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on the server) and a
client program (resides on the client).

Transport Layer − This layer connects the client and the server. It manages the existing connection
and also sets up new connections.

Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.

Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.

RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to
the remote object.

Q.5 Write a note on Protocol handler.


> A protocol handler is a software component that handles requests from a computer program or
web browser to access a resource or service via a specific protocol, such as HTTP, FTP, or mailto.
Protocol handlers act as intermediaries between applications and the underlying network protocols,
enabling communication and data exchange.

Here are some key points about protocol handlers:

- They allow applications to access resources or services without needing to implement the
underlying protocol logic.
- Protocol handlers can be built into web browsers, email clients, or other software applications.

- They can also be installed as add-ons or plugins to extend the capabilities of an application.

- Protocol handlers can perform tasks such as URL rewriting, authentication, and data
encoding/decoding.

Examples of protocol handlers include:

- HTTP handlers for web requests

- FTP handlers for file transfers

- Mailto handlers for email links

- SFTP handlers for secure file transfers

In summary, protocol handlers play a crucial role in enabling communication between applications
and network services, making it easier for developers to access and interact with various
resources and protocols.

Q.6 Describe the use of URL class.


> The URL class is a programming construct used to represent and manipulate Uniform Resource
Locators (URLs). It provides a way to work with URLs in a convenient and object-oriented manner.

Here are some common uses of the URL class:

1. Parsing URLs: Breaking down a URL into its components, such as protocol, host, port, path, query,
and fragment.

2. Building URLs: Constructing a URL from its components, allowing for easy creation of URLs.

3. URL Validation: Checking whether a URL is valid and properly formatted.

4. URL Comparison: Comparing two URLs to determine if they are equivalent.

5. Extracting URL parts: Retrieving specific parts of a URL, such as the domain, path, or query string.

6. Encoding and Decoding: Handling URL encoding and decoding tasks, such as converting special
characters to their escaped forms.

7. Resolving Relative URLs: Converting relative URLs to absolute URLs, taking into account a base
URL.

The URL class is commonly used in web development, network programming, and any scenario
where URLs need to be manipulated or analyzed.

Programming languages like Java, Python, and C# have their own implementations of the URL class,
with slightly different methods and properties.
Q.7 Explain the following classes with their use.
i. URLConnection class
ii. DatagramSocket and DatagramPacket class
>

Q.8 Explain Socket, ServerSocket, InetAddress classes. Write a java program to find an IP
address of the machine on which the program runs.
>

Q.9 Difference between socket and server socket.


>

UNIT 2
Q.1 What is JDBC? WAP to get data from the user & save it into the table.
Q.2 Explain Statement in context of JDBC. Difference between prepared & callable
statements.
Q.3 Retrieve data which is stored in the database table using Resultset.
Q.4 Explain different types of JDBC drivers.
Q.5 What is a ResultSet in JDBC? How do you process a ResultSet?
Q.6 Explain JDBC Architecture.
Q.7 What are the differences between Java Bean and basic java class? Explain Java Bean
Architecture.
Q.8 Explain the use of CallableStatement and PreparedStatement with example.
Q.9 Show the use of PreparedStatement object to run precompiled SQL statement. Also
write example of java snippet for PreparedStaement.
Q.10 Explain ResultSetMetaData with suitable program.
Q.11 Explain JDBC Transaction.
Q.12 What is ResultSet interface. Write various method for ResultSet interface. Write a
code to update record using this interface.
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.

UNIT 4

Q.1 What is JSP? Explain Life cycle of JSP.

1. **Translation**: When a JSP file is first accessed or modified, it undergoes translation. The JSP

container translates the JSP file into a servlet class. During this phase:

- JSP elements (HTML markup, JSP tags, scriptlets, expressions, declarations) are parsed and
converted into corresponding Java code.

- The translated servlet class is generated and compiled by the JSP container.

2. **Compilation**: The translated servlet class is compiled into bytecode (.class file) by the Java

compiler. This bytecode represents the executable servlet code.

3. **Initialization**: When the web application containing the JSP is deployed or started, the servlet

container initializes the JSP servlet by calling its `init()` method. This method is typically used for

performing one-time initialization tasks, such as setting up resources, loading configuration

parameters, or establishing database connections.

4. **Request Handling**: When a client sends an HTTP request for the JSP page, the servlet

container handles the request by invoking the `service()` method of the JSP servlet. This method

takes the request and response objects as parameters and is responsible for generating the dynamic

content of the JSP page.

5. **Execution**: During the execution phase, the JSP servlet processes the request, executes any

Java code (scriptlets, expressions, method calls) embedded within the JSP page, and generates the

corresponding HTML output. This HTML output is then sent back to the client browser as part of the

HTTP response.

6. **Destruction**: When the web application is stopped or undeployed, the servlet container calls

the `destroy()` method of the JSP servlet. This method is used for performing cleanup tasks, releasing

resources, or closing connections that were initialized during the initialization phase.

Q.2 Write a program to create a java class and call it in the JSP page.
>

Q.3 Explain Core tag library.


>The Core tag library is a part of the JSP Standard Tag Library (JSTL) that provides tags for common
tasks such as:

- Variable support (set, get, remove)

- Flow control (if, choose, foreach)

- URL management (import, redirect)

- Functions (string manipulation, math operations)


Some of the commonly used Core tags are:

- <c:set>: Sets a variable

- <c:get>: Gets a variable

- <c:remove>: Removes a variable

- <c:if>: Conditional statement

- <c:choose>: Conditional statement with multiple options

- <c:foreach>: Loops over a collection

- <c:import>: Imports a URL

- <c:redirect>: Redirects to a URL

- <c:out>: Outputs a value

- <c:catch>: Catches an exception

These tags provide a way to perform common tasks in a JSP page without the need for scripting.
They make the code more readable, maintainable, and reusable.

For example:

<c:set var="name" value="John" />

<c:out value="${name}" /> // Outputs "John"

<c:if test="${name == 'John'}">

<c:out value="Hello, John!" />

</c:if>

<c:foreach items="${list}" var="item">

<c:out value="${item}" />

</c:foreach>

In this example, the Core tags are used to set a variable, output a value, perform a conditional
statement, and loop over a collection.
Q.4 What is the difference between a Servlet and a JSP? When would you use one over
the other?

Q.5 Difference between @include and <jsp:include>

Q.6 How do you pass data from a Servlet to a JSP page?


Q.7 Explain Use of scriptlet and expression tag. Explain it with an example.
>

Q.8 Explain Directives. Give its type and explain any one in detail.
>

Q.9 Explain JSP Object scope: (i) Page (ii) Request (iii) Session (iv) Application with
example.
>

Q.10 Show the use of JSP page directive tag with its attributes.
>

Q.11 Show the use of JSP inbuilt objects: request and response, with their use in
Application.
>

Q.12 What is XML tag library? Explain the XML core tags and show their use.
>

Q.13 Write a JSP page to display your semester mark sheet. Give the necessary
files to deploy it.
>

Q.14 Explain the action tags used to access the JavaBeans from a JSP page with
example.
>

Q.15 Show the use of JSP inbuilt objects: request and response, with their use in
application.
>

Q.16 Explain transaction handling using JSTL.


>

Q.17 Discuss JSP Exception Handling.


>

You might also like