W22 Answer For Gtu

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

W22 answer

Q.1 (a)
1) How do you get the IP address of a machine from its hostname?

1) To obtain the IP address of a machine from its hostname, you can use the `InetAddress` class in
Java. Here's a sample code snippet:

String hostname = "example.com";

InetAddress address = InetAddress.getByName(hostname);

String ipAddress = address.getHostAddress();

System.out.println("IP Address of " + hostname + " is: " + ipAddress);

2) List out the important methods of HttpServletResponse.

Important methods of HttpServletResponse include:

- `setStatus(int sc)`: Sets the status code of the response.

- `setContentType(String type)`: Sets the content type of the response being sent to the client.

- `getWriter()`: Returns a PrintWriter object that can send character text to the client.

- `sendRedirect(String location)`: Sends a temporary redirect response to the client using the
specified redirect location URL.

3) What are the attributes for the JSP page directive?

In JSP, the page directive is used to provide global information about a JSP page to the container.
The main attributes of the page directive are:

1. **`import`**: Specifies the classes to import.

2. **`session`**: Specifies whether the page participates in a session (`true` by default).

3. **`buffer`**: Sets the buffer size (`8kb` by default).

4. **`autoFlush`**: Determines whether the buffer is flushed automatically when full (`true` by
default).

5. **`isThreadSafe`**: Specifies whether the JSP page is thread-safe (`true` by default).

6. **`info`**: Provides additional information about the JSP page.


7. **`errorPage`**: Specifies the URL of the error page.

8. **`isErrorPage`**: Indicates whether the current page is an error page (`false` by default).

9. **`contentType`**: Sets the content type and character encoding for the response (`text/html;
charset=UTF-8` by default).

10. **`language`**: Specifies the scripting language used (`java` by default).

11. **`extends`**: Defines the superclass of the servlet.

12. **`pageEncoding`**: Specifies the character encoding of the page (`UTF-8` by default).

These attributes allow you to control various aspects of the JSP page, such as the response format,
session handling, and error handling.

(b)

1) What is the function of a SessionFactory object? How will you obtain such an object?

The SessionFactory object in Hibernate serves the crucial function of managing Hibernate sessions. It
acts as a factory for session objects and is responsible for creating and managing sessions
throughout the application lifecycle.

To obtain a SessionFactory object, you typically use the `buildSessionFactory()` method provided by
Hibernate's Configuration class. Here's a concise example:

Configuration configuration = new Configuration().configure();

SessionFactory sessionFactory = configuration.buildSessionFactory();

In this code snippet, the `configure()` method loads Hibernate configuration settings from the
default configuration file (`hibernate.cfg.xml`). Then, the `buildSessionFactory()` method creates a
SessionFactory object based on the provided configuration.

2) How can you apply JSF Input Validation using input validators?

JSF (JavaServer Faces) provides a built-in mechanism for input validation using input validators.
Validators are used to ensure that the data entered by users meets specified criteria before it is
processed by the server. Here's how you can apply JSF input validation using input validators for 3
marks:
1. **Define a Validator**: First, you need to create a validator class by implementing the `Validator`
interface. This interface defines a single method, `validate()`, which performs the validation logic. For
example, let's create a validator to validate email addresses:

import javax.faces.component.UIComponent;

import javax.faces.context.FacesContext;

import javax.faces.validator.Validator;

import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {

@Override

public void validate(FacesContext context, UIComponent component, Object value) throws


ValidatorException {

String email = (String) value;

// Perform email validation logic here

if (!email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")) {

throw new ValidatorException(new FacesMessage("Invalid email format"));

2. **Attach Validator to Input Component**: Next, you need to attach the validator to the input
component in your JSF page. This is done using the `<f:validator>` tag. For example, to apply the
`EmailValidator` to an inputText component:

```xml

<h:inputText id="email" value="#{bean.email}">

<f:validator validatorId="emailValidator" />

</h:inputText>
In this code snippet, `emailValidator` is the ID of the validator defined in the `faces-config.xml`
configuration file.

3. **Apply the Validator to Input Fields**:

In the JSF page where you want to apply validation, use the `f:validator` tag to attach the validator to
the input field.

```xml

<h:inputText value="#{bean.inputValue}">

<f:validator validatorld="customValidator" />

</h:inputText>

4. **Display Error Messages**: Finally, you should handle validation errors by displaying appropriate
error messages to the user. This can be achieved using the `<h:message>` or `<h:messages>` tag. For
example:

```xml

<h:inputText value="#{bean.inputValue}">

<f:validator validatorld="customValidator" />

</h:inputText>

With these steps, when the form is submitted, the custom validator will be invoked to validate the
input field. If validation fails, a `ValidatorException` is thrown with an appropriate error message,
which will be displayed to the user. Otherwise, the input is considered valid, and the form
submission continues.

(c) What do you mean by session tracking? What are the session tracking techniques?
Demonstrate any of them

Session tracking is a mechanism used in web development to maintain the state of a user's
interaction with a website across multiple requests. It enables the server to recognize and
remember specific users, their preferences, and their actions during a browsing session. Session
tracking is essential for creating personalized and interactive web experiences.

Several techniques are employed for session tracking:

1. **Cookies**: Cookies are small pieces of data stored on the client's browser. They contain
information such as session IDs or user preferences and are sent back and forth between the client
and server with each HTTP request and response. Cookies are widely used for session tracking due to
their simplicity and versatility.
2. **URL Rewriting**: In this technique, the session ID is appended to URLs as a query parameter.
Each URL generated by the server contains the session ID, allowing the server to associate
subsequent requests with the correct session. URL rewriting is transparent to users and doesn't
require browser cookie support.

3. **Hidden Form Fields**: Session IDs or other session-related data can be stored as hidden fields
within HTML forms. When the form is submitted, the session data is sent back to the server along
with the form data. This technique is useful when cookies are disabled or not preferred.

Let's demonstrate session tracking using cookies in Java Servlets:

import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) {

// Create or retrieve the session

HttpSession session = request.getSession(true);

// Set session attributes

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

session.setAttribute("cartItems", 5);

// Retrieve session attributes

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

int cartItems = (int) session.getAttribute("cartItems");

// Output session attributes

System.out.println("Username: " + username);

System.out.println("Cart Items: " + cartItems);

// Set session expiration time

session.setMaxInactiveInterval(30 * 60); // 30 minutes


// Invalidate session

session.invalidate();

In this servlet example, we create or retrieve the session using `request.getSession(true)`. We then
set session attributes like "username" and "cartItems" using `setAttribute()`. Later, we retrieve these
attributes using `getAttribute()`. We can also set the session expiration time using
`setMaxInactiveInterval()`, and invalidate the session using `invalidate()`. Through cookies, the server
can maintain the session state across multiple client requests.

Q.2

(a) What are the differences between a TCP socket and UDP socket? How are they created in Java?

In Java, both TCP and UDP sockets can be created using the Socket and DatagramSocket
classes, respectively:

 TCP Socket Creation in Java:


import java.io.*;

import java.net.*;

Socket socket = new Socket("hostname", portNumber);

 UDP Socket Creation in Java:

import java.net.*;

DatagramSocket socket = new DatagramSocket();

In TCP socket creation, you specify the hostname and port number to establish a connection with
the server. In UDP socket creation, you simply create a DatagramSocket object, which can be used
for sending and receiving UDP packets.

(b) Differentiate ServletConfig and ServletContext.

(c) What is connection URL? How do you make a database connection? Explain various ways to
make the database connection using JDBC code snippets.
A connection URL (Uniform Resource Locator) in the context of database connectivity specifies the
address and other parameters required to establish a connection to a database. It typically includes
information such as the database driver, host address, port number, database name, and optional
authentication credentials.

To make a database connection using JDBC (Java Database Connectivity), you need to follow these
steps:

Steps to Connect Java Application with Database


Below are the steps that explains how to connect to Database in Java:
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections

Here are various ways to make a database connection using JDBC code snippets
Apologies for misunderstanding your question earlier. Let me explain various ways to make a
database connection using JDBC code snippets:

1. **Using DriverManager**:

This is the most common method to establish a database connection. It involves loading the JDBC
driver, specifying the connection URL, username, and password.

import java.sql.*;

// Load the JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection using DriverManager

String url = "jdbc:mysql://localhost:3306/mydatabase";

String username = "username";

String password = "password";

Connection connection = DriverManager.getConnection(url, username, password);

2. **Using DataSource**:

DataSource provides an alternative way to obtain a database connection. It's typically used in
enterprise applications and is managed by the application server or container.

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;

// Create and configure DataSource

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
dataSource.setUsername("username");

dataSource.setPassword("password");

// Get connection from DataSource

Connection connection = dataSource.getConnection();

3. **Using Connection Pooling**:

Connection pooling improves performance by reusing existing database connections rather than
creating new ones for each request.

```java

import java.sql.*;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;

// Create and configure connection pool

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");

dataSource.setUsername("username");

dataSource.setPassword("password");

dataSource.setInitialSize(10); // Set initial pool size

// Get connection from connection pool

Connection connection = dataSource.getConnection();

```

4. **Using JNDI (Java Naming and Directory Interface)**:


JNDI allows applications to access objects in a naming/directory service. It's commonly used in Java
EE applications to obtain database connections from the application server's connection pool.

```java

import javax.naming.*;

import javax.sql.DataSource;

// Lookup DataSource from JNDI

Context ctx = new InitialContext();

DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/mydatabase");

// Get connection from DataSource

Connection connection = dataSource.getConnection();

```

**5. Using the Class.forName() method**


The Class.forName() method is used to load the driver class into memory. Once
the driver class is loaded, it is automatically registered with the DriverManager.
import java.sql.*;

public class JDBCExample {

public static void main(String[] args) throws Exception {

// Load the driver class

Class.forName("com.mysql.cj.jdbc.Driver");

// Create a connection to the database


Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "myusername",
"mypassword");

// Create a statement

Statement statement = connection.createStatement();

// Execute the query

ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");

// Process the results

while (resultSet.next()) {

System.out.println(resultSet.getString("name"));

// Close the connection

connection.close();

6. Using the DriverManager.registerDriver() method

The DriverManager.registerDriver() method is used to register a driver with the


DriverManager. This method is used if you are using a non-JDK compliant JVM.
import java.sql.*;

public class JDBCExample {

public static void main(String[] args) throws Exception {


// Register the driver

DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

// Create a connection to the database

Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "myusername",
"mypassword");

// Create a statement

Statement statement = connection.createStatement();

// Execute the query

ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");

// Process the results

while (resultSet.next()) {

System.out.println(resultSet.getString("name"));

// Close the connection

connection.close();

These are some of the common ways to make a database connection using JDBC in Java. Each
approach has its advantages and is suitable for different scenarios based on the application's
requirements and environment.

Or

(c) What is JDBC driver? Explain its role and compare various JDBC drivers.
A JDBC driver is a software component that enables Java applications to interact with
databases. It acts as a bridge, translating Java calls into database-specific commands. The
JDBC driver interface allows applications to execute queries and update data across
different database systems123.

Role of JDBC Driver

The role of a JDBC driver includes:

 Connecting to a Data Source: It provides the connection to the database.


 Translating Queries: It translates the SQL statements from Java into the format understood
by the database.
 Processing Results: It handles the data retrieved from the database and presents it to the
Java application in a suitable format42.

JDBC Driver
A JDBC driver is a software component that acts as a bridge between a Java application and
a database. It translates Java method calls related to database operations (like connecting,
executing queries, and manipulating data) into commands understood by the specific
database system. This enables Java applications to interact with various databases
regardless of their underlying architecture or protocol.
Role of a JDBC Driver
 Translation: Converts Java code into database-specific commands.
 Communication: Mediates communication between the Java application and the database
server.
 Abstraction: Provides a standard interface for working with different databases.
 Connecting to a Data Source: It provides the connection to the database.
 Translating Queries: It translates the SQL statements from Java into the format understood by
the database.

Comparison of JDBC Driver Types

Type Description Advantages Disadvantages

Uses the ODBC driver - Works with any - Less performant due to
1. JDBC-ODBC
manager to connect to database that has an extra translation layer. -
Bridge Driver
the database. ODBC driver. Deprecated approach.

2. Native-API Part Java, part native - Faster than bridge - Platform-dependent


Driver (Partially code (C/C++). driver due to native due to native code. -
Java Driver) code interaction. Requires installation of
native libraries.

- Platform-
3. Network Pure Java driver that - Can introduce
independent. - More
Protocol Driver communicates with a additional overhead due
secure as database
(Pure Java middleware server on to middleware layer. -
credentials don't
Middleware the database server Requires configuration
reside on the client
Driver) side. of middleware server.
machine.

- Most performant
4. Thin Driver
Pure Java driver that and widely used type. - Limited functionality
(Pure Java
connects directly to - Platform- compared to some
Direct-to-
the database server. independent. - Easy to native-API drivers.
Database Driver)
use and manage.

Q.3

(a) What is the use of PreparedStatement? How will you use it?

The PreparedStatement in Java is used for executing pre-compiled SQL statements. This
interface extends the Statement class and allows you to execute parameterized queries with
ease, improving performance and security, particularly against SQL injection attacks 12.

Here’s how you can use a PreparedStatement:

1. Create a Connection: Establish a connection to the database using


DriverManager.getConnection().
2. Prepare the Statement: Create a PreparedStatement object using
Connection.prepareStatement(), passing an SQL query with placeholders (?).
3. Set Parameters: Use setter methods like setInt(), setString(), etc., to set values for the
placeholders.
4. Execute the Query: Call executeQuery() for SELECT statements or executeUpdate() for
DML statements like INSERT, UPDATE, DELETE.
5. Process the Results: If executing a SELECT query, process the ResultSet returned.
6. Close the Resources: Close the PreparedStatement and Connection objects to release
resources.

Here’s an example code snippet using PreparedStatement:

import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YourDatabase";
String user = "username";
String password = "password";
String sql = "SELECT * FROM Employees WHERE id = ?";

try (Connection conn = DriverManager.getConnection(url, user, password);


PreparedStatement pstmt = conn.prepareStatement(sql)) {

pstmt.setInt(1, 10); // Set the id parameter


ResultSet rs = pstmt.executeQuery();

while (rs.next()) {
// Process the result set
String name = rs.getString("name");
System.out.println("Employee Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

(b) What is filter? How will you configure filter using deployment descriptor? 04

A filter in the context of web applications is a reusable piece of code that can transform the
content of HTTP requests, responses, and header information going to and from a server.
Filters are often used to perform tasks such as logging, authentication, data compression,
encryption/decryption, and input validation1.

To configure a filter using a deployment descriptor, you would typically modify the web.xml
file of your Java web application. Here’s how you can do it:

1. Declare the Filter: Define the filter in the web.xml file with <filter> and <filter-name>
tags.
2. Specify the Filter Class: Use the <filter-class> tag to specify the fully qualified name of
the class that implements the filter.
3. Configure Initialization Parameters: If needed, use <init-param> tags within the <filter>
tag to set initialization parameters.
4. Map the Filter: Use <filter-mapping> to map the filter to a URL pattern or a servlet
name.
5. Set the URL Pattern: Within the <filter-mapping>, use the <url-pattern> tag to specify the
URL pattern that the filter should apply to.

Here’s an example of how the web.xml might look:

<web-app>
<!-- Filter Declaration -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</init-param>
</filter>

<!-- Filter Mapping -->


<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

In this example, MyFilter is the name given to the filter, and com.example.MyFilter is the fully
qualified class name of the filter implementation. The filter is mapped to all URLs (/*) within
the application23.

Remember, the order of filter mappings in web.xml can affect the order in which filters are
applied. Also, ensure that your filter class correctly implements the javax.servlet.Filter interface
and the necessary methods (init, doFilter, and destroy).

(c) What are the directive tags of JSP? Write a JSP page to demonstrate the use of them

In JSP (JavaServer Pages), directive tags are used to provide the JSP container with
instructions for processing the JSP page. There are three types of directive tags:

1. Page Directive: Defines page-dependent attributes, like the scripting language, error
pages, and the buffer size.
2. Include Directive: Includes a file during the translation phase.
3. Taglib Directive: Declares a tag library that defines custom actions.

Here’s an example of a JSP page demonstrating the use of these directives:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" isELIgnored="false" %>
<%@ page import="java.util.Date" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
<title>Directive Tags Example</title>
</head>
<body>
<h2>JSP Directive Tags Example</h2>
<!-- Page Directive: Importing Date class -->
Today's date: <%= new Date() %>

<!-- Include Directive: Including a header file -->


<%@ include file="header.jsp" %>

<!-- Taglib Directive: Using JSTL core library -->


<c:out value="${'Hello, JSP!'}" />

<!-- Page Directive: Error page and buffer size -->


<%@ page errorPage="error.jsp" buffer="16kb" %>
</body>
</html>

In this example:

 The page directive at the top sets the language, content type, encoding, and EL
ignoring.
 The import attribute of the page directive imports the Date class from the java.util
package.
 The include directive includes the content of header.jsp into the current page.
 The taglib directive declares the use of the JSTL core library and sets the prefix c for
its tags.
 The errorPage and buffer attributes of the page directive specify the error page and
buffer size respectively123

OR

Q.3

(a) What is the use of CallableStatement? How will you use it? 03

The CallableStatement in Java is used to execute stored procedures and functions in a


database. Stored procedures are precompiled SQL statements that reside in the database,
which can improve performance and encapsulate business logic12.

Here’s how you can use a CallableStatement:

1. Create a Connection: Establish a connection to the database using


DriverManager.getConnection().
2. Prepare the Callable Statement: Create a CallableStatement object using
Connection.prepareCall(), passing an SQL query in the form of a call to the stored
procedure.
3. Set Parameters: If the stored procedure has input parameters, use methods like
setInt(), setString(), etc., to set their values. For output parameters, register them with
registerOutParameter().
4. Execute the Callable Statement: Call execute() to run the stored procedure.
5. Retrieve Output Parameters: If there are output parameters, retrieve their values
after execution using methods like getInt(), getString(), etc.
6. Close the Resources: Close the CallableStatement and Connection objects to release
resources.

Here’s an example code snippet using CallableStatement:

import java.sql.*;

public class CallableStatementExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YourDatabase";
String user = "username";
String password = "password";
String sql = "{ call your_stored_procedure(?, ?) }";

try (Connection conn = DriverManager.getConnection(url, user, password);


CallableStatement cstmt = conn.prepareCall(sql)) {

// Set input parameter


cstmt.setInt(1, 10);
// Register output parameter
cstmt.registerOutParameter(2, Types.VARCHAR);

// Execute the callable statement


cstmt.execute();

// Retrieve output parameter


String result = cstmt.getString(2);
System.out.println("Stored Procedure Output: " + result);

} catch (SQLException e) {
e.printStackTrace();
}
}
}

(b) What is FilterConfig? How will you use it? 04

FilterConfig is an interface in Java Servlet API that provides configuration information for a
filter. It is used by the web container to pass information to a filter during initialization. This
object allows the filter to access initialization parameters from the deployment descriptor
(web.xml) and the servlet context12.

Here’s how you can use FilterConfig:

1. Initialization: When a filter is instantiated, the web container calls the init method of
the filter and passes the FilterConfig object to it.
2. Accessing Initialization Parameters: Use getInitParameter method to retrieve
initialization parameter values defined in web.xml.
3. Accessing the Filter Name: Use getFilterName to get the name of the filter as defined
in the deployment descriptor.
4. Accessing the Servlet Context: Use getServletContext to obtain a reference to the
ServletContext in which the filter is executing.

Here’s an example code snippet demonstrating the use of FilterConfig:

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

public class MyFilter implements Filter {


private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig) throws ServletException {


this.filterConfig = filterConfig;
}

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


throws IOException, ServletException {

// Accessing an initialization parameter


String initParamValue = filterConfig.getInitParameter("paramName");

// Proceed with the filter chain or perform some action


if ("someValue".equals(initParamValue)) {
// Perform some action
} else {
// Continue with the filter chain
chain.doFilter(request, response);
}
}

public void destroy() {


// Clean up resources
}
}

In the web.xml, you would configure the filter and its initialization parameters like this:

<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
<init-param>
<param-name>paramName</param-name>
<param-value>someValue</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(c) What are the implicit objects of JSP? Write a JSP page to demonstrate the use them.

In JSP (JavaServer Pages), implicit objects are pre-defined variables that the JSP container
provides to developers, allowing them to access various objects associated with the page
without having to explicitly declare them. There are nine standard implicit objects in JSP:

1. out: JspWriter object to send content in the response.


2. request: HttpServletRequest object that represents the client’s request.
3. response: HttpServletResponse object for the servlet’s response.
4. config: ServletConfig object containing the servlet’s configuration.
5. application: ServletContext object associated with the web application.
6. session: HttpSession object for maintaining user sessions.
7. pageContext: Provides access to all the namespaces associated with a JSP page.
8. page: Equivalent to this in servlets, refers to the instance of the generated servlet.
9. exception: Throwable object representing the exception that triggered the error page.

Here’s an example of a JSP page demonstrating the use of some implicit objects:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>Implicit Objects Example</title>
</head>
<body>
<h2>Using Implicit Objects in JSP</h2>
<!-- Using 'out' to write content to the response -->
<% out.println("This is written using the 'out' implicit object."); %>

<!-- Using 'request' to get parameter values -->


<p>Client's request method: <%= request.getMethod() %></p>

<!-- Using 'session' to get session ID -->


<p>Session ID: <%= session.getId() %></p>

<!-- Using 'application' to get context path -->


<p>Application Context Path: <%= application.getContextPath() %></p>

<!-- Using 'config' to get servlet's init parameter -->


<p>Servlet Init Parameter: <%= config.getInitParameter("someParam")
%></p>

<!-- Using 'pageContext' to get attribute -->


<% pageContext.setAttribute("myAttr", "Hello, PageContext!"); %>
<p>PageContext Attribute: <%= pageContext.getAttribute("myAttr") %></p>

<!-- Using 'page' to call a method on the current servlet instance -->
<% pageContext.getOut().print("This is equivalent to using 'out'."); %>

<!-- Error handling using 'exception' -->


<% if(exception != null) { %>
<p>Error Message: <%= exception.getMessage() %></p>
<% } %>
</body>
</html>
Q.4
(a) What is EL? Write a code snippet to show the use of method expressions
in JSF page.

EL stands for Expression Language, which is a powerful scripting language used in


JavaServer Faces (JSF) to bind UI components to data sources such as managed beans. It
provides a way to simplify the accessibility of data and functionalities of the Java codebase
within the JSF pages1.

Method expressions in EL are used to invoke methods of a backing bean from the JSF page.
They are typically used in attributes like action or actionListener of a UI component,
such as a button or link.

Here’s a code snippet demonstrating the use of method expressions in a JSF page:

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<html>
<head>
<title>Method Expression Example</title>
</head>
<body>
<h:form>
<!-- Method expression used in the 'action' attribute of a command
button -->
<h:commandButton value="Submit" action="#{myBean.submitAction}" />
</h:form>
</body>
</html>
.
(b) How will you use <h:commandButton> and <h:dataTable>? 04

In JSF (JavaServer Faces), <h:commandButton> and <h:dataTable> are commonly used


tags for creating interactive forms and displaying data in a tabular format, respectively.

Using <h:commandButton>

The <h:commandButton> tag renders an HTML submit button that can be used to perform
actions like submitting a form or calling a method in a managed bean. Here’s an example of
how to use it:

<h:form>
<!-- CommandButton to submit the form and invoke a method in a managed
bean -->
<h:commandButton value="Submit" action="#{bean.submitMethod}" />
</h:form>

In this snippet, when the “Submit” button is clicked, the submitMethod of the bean managed
bean will be invoked1.
Using <h:dataTable>

The <h:dataTable> tag is used to display collections of data objects in a table. Each row
represents an element in the collection, and each column corresponds to a property of the
element. Here’s an example:

<h:dataTable value="#{bean.dataList}" var="item">


<!-- Define columns with headers and data fields -->
<h:column>
<f:facet name="header">Column Header</f:facet>
#{item.property}
</h:column>
<!-- Add more columns as needed -->
</h:dataTable>

These tags are powerful components of JSF that help in creating dynamic web pages that
interact with backend Java code seamlessly.

(c) Develop a web application as following to demonstrate the use of .


 Create a Java Bean named Employee with attributes name and age.
 Create a web page to set the properties of Employee using .
 Create a web page to display the properties of Employee using .

Certainly! Let’s create a simple web application to demonstrate the use of <jsp:useBean>
with an Employee Java Bean. We’ll create a JSP page to set the properties of the Employee
and another JSP page to display those properties.

1. Create the Employee Java Bean:


o The Employee class will have attributes name and age.
o We’ll provide getter and setter methods for these attributes.

package com.example;

public class Employee {


private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
2. Create a JSP Page to Set Properties (setEmployee.jsp):
o In this JSP page, we’ll use <jsp:useBean> to create an Employee object and
set its properties.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<%@ page import="com.example.Employee" %>

<!DOCTYPE html>
<html>
<head>
<title>Set Employee Properties</title>
</head>
<body>
<h2>Set Employee Properties</h2>
<jsp:useBean id="employee" class="com.example.Employee" />
<jsp:setProperty name="employee" property="name" value="John Doe" />
<jsp:setProperty name="employee" property="age" value="30" />
<p>Name: <%= employee.getName() %></p>
<p>Age: <%= employee.getAge() %></p>
</body>
</html>

3. Create a JSP Page to Display Properties (displayEmployee.jsp):


o In this JSP page, we’ll use <jsp:useBean> to access the Employee object and
display its properties.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<%@ page import="com.example.Employee" %>

<!DOCTYPE html>
<html>
<head>
<title>Display Employee Properties</title>
</head>
<body>
<h2>Display Employee Properties</h2>
<jsp:useBean id="employee" class="com.example.Employee" />
<p>Name: <%= employee.getName() %></p>
<p>Age: <%= employee.getAge() %></p>
</body>
</html>

4. Deploy and Run:


o Deploy your web application (e.g., using Apache Tomcat).
o Access setEmployee.jsp to set the properties.
o Then access displayEmployee.jsp to see the displayed properties.

Or
Q.4
(a) What is JSTL? Write a code snippet to show the use of flow control
tags. 03

JSTL (JavaServer Pages Standard Tag Library) is a set of custom tags that simplify JSP
development by providing common functionalities like flow control, database operations, and
more. JSTL tags can be embedded in JSP pages just like other HTML tags, making it
convenient for front-end developers to work with HTML-like tags for including logic in web
pages without writing extensive Java code.

Let’s explore some of the flow control tags provided by JSTL Core:

1. <c:if>: Executes enclosed content if the specified condition evaluates to true.


2. <c:choose>, <c:when>, and <c:otherwise>**: Used for conditional branching.
3. <c:forEach>: Iterates over a collection and executes the enclosed content for each
item.
4. <c:forTokens>: Splits a string into tokens and iterates over them.
5. <c:catch>: Catches exceptions thrown within its enclosure.
6. <c:set>: Declares scoped variables.
7. <c:remove>: Removes a specified variable.
8. <c:redirect>: Redirects the response to a specified URL.

Here’s an example demonstrating the use of <c:if> and <c:forEach>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
<title>JSTL Flow Control Example</title>
</head>
<body>
<h2>Flow Control Example</h2>

<!-- Using <c:if> -->


<c:set var="age" value="25" />
<c:if test="${age lt 30}">
<p>You are young!</p>
</c:if>

<!-- Using <c:forEach> -->


<c:set var="colors" value="Red,Green,Blue" />
<ul>
<c:forEach items="${fn:split(colors, ',')}" var="color">
<li>${color}</li>
</c:forEach>
</ul>
</body>
</html>

In this example:

 The <c:if> tag checks if the age is less than 30 and displays a message accordingly.
 The <c:forEach> tag splits the colors string and iterates over the resulting tokens to
create a list.
(b) Write a code snippet to show the use of JSF action event. 04

Certainly! Below is a code snippet demonstrating the use of JSF action events with
<h:commandButton>:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>JSF Action Event Example</title>
</head>
<body>
<h2>JSF Action Event Example</h2>

<!-- Using <h:commandButton> with action -->


<h:form>
<h:commandButton value="Submit" action="#{myBean.submitAction}" />
</h:form>
</body>
</html>

In this example:

 When the “Submit” button is clicked, the submitAction method in the myBean
managed bean will be invoked.
 You can replace myBean with your actual managed bean name and adjust the method
name according to your application’s requirements.

(c) Develop a web application as following to demonstrate the use of JSTL SQL tag library.

 Create a web page to store the registration detail (Name, email and contact number) of user in
the database.

 Create a web page for user to update registration detail in the database.

 Create a web page to display the list of all registered users.

To demonstrate the use of the JSTL SQL tag library, we’ll develop a simple web application
with three pages: one for user registration, one for updating registration details, and one to
display a list of all registered users. Below are the code snippets for each page:

1. User Registration Page (register.jsp)


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Register User</h2>
<form action="register.jsp" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Contact Number: <input type="text" name="contact"><br>
<input type="submit" value="Register">
</form>

<sql:update dataSource="${dataSource}" var="updatedRows">


INSERT INTO Users (name, email, contact_number) VALUES (?, ?, ?)
<sql:param value="${param.name}" />
<sql:param value="${param.email}" />
<sql:param value="${param.contact}" />
</sql:update>

<c:if test="${updatedRows > 0}">


<p>User registered successfully!</p>
</c:if>
</body>
</html>

2. Update Registration Details Page (update.jsp)


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<title>Update Registration Details</title>
</head>
<body>
<h2>Update User Details</h2>
<form action="update.jsp" method="post">
User ID: <input type="text" name="id"><br>
New Email: <input type="text" name="email"><br>
New Contact Number: <input type="text" name="contact"><br>
<input type="submit" value="Update">
</form>

<sql:update dataSource="${dataSource}" var="updatedRows">


UPDATE Users SET email = ?, contact_number = ? WHERE id = ?
<sql:param value="${param.email}" />
<sql:param value="${param.contact}" />
<sql:param value="${param.id}" />
</sql:update>

<c:if test="${updatedRows > 0}">


<p>User details updated successfully!</p>
</c:if>
</body>
</html>

3. Display Registered Users Page (listUsers.jsp)


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<title>List of Registered Users</title>
</head>
<body>
<h2>Registered Users</h2>
<sql:query dataSource="${dataSource}" var="result">
SELECT * FROM Users
</sql:query>

<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact Number</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}" /></td>
<td><c:out value="${row.name}" /></td>
<td><c:out value="${row.email}" /></td>
<td><c:out value="${row.contact_number}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Q.5

(a) What is Spring AOP? What are Join points and Point cuts? 03

Spring AOP (Aspect-Oriented Programming) is a programming paradigm that aims to


increase modularity by allowing the separation of cross-cutting concerns. It does this by
adding additional behavior to existing code without modifying the code itself, instead
declaring the new code and behaviors separately. Spring’s AOP framework helps implement
these cross-cutting concerns, such as logging, security, or transaction management1.

Join points are specific points in the execution of the application, like method execution or
exception handling, where an aspect can be applied. In Spring AOP, a join point always
represents a method execution2.

Pointcuts are expressions that are used to select one or more join points. They define
“where” and “when” the advice (additional behavior) should be applied. Pointcuts can be
specified using annotations or XML configuration3.
(b) What is dependency Injection? What is the role IoC container in Spring? 04

Dependency Injection (DI) is a design pattern in software development where a component's


dependencies are provided externally rather than being created internally. In other words, instead of
a component creating its dependencies, it receives them from an external source. This promotes
loose coupling between components and enhances modularity, testability, and maintainability of the
codebase.

The role of the Inversion of Control (IoC) container in Spring is central to the implementation of DI.
The IoC container manages the lifecycle of application objects (beans) and their dependencies. It
follows the principle of inversion of control, where the control over object creation and
management is delegated to the container rather than being handled by the application code.

Key responsibilities of the IoC container in Spring include:

1. **Object Creation**: The IoC container instantiates beans defined in the Spring configuration
files, resolving their dependencies and managing their lifecycle.

2. **Dependency Injection**: The IoC container performs dependency injection by providing


dependencies to beans at runtime. It injects dependencies into beans either through constructor
injection, setter injection, or field injection based on the configuration.

3. **Lifecycle Management**: The IoC container manages the lifecycle of beans, including their
initialization, destruction, and scope management (singleton, prototype, request, session, etc.).

4. **Configuration Management**: The IoC container manages the configuration of beans, including
their properties, dependencies, and other settings specified in the Spring configuration files.

In summary, DI and the IoC container in Spring work together to promote loose coupling,
modularity, and flexibility in application development. DI enables externalized management of
dependencies, while the IoC container orchestrates the creation, configuration, and lifecycle
management of beans within the application context.
(c) What are the different Hibernate interfaces? Explain their role in brief. 07

Hibernate is a powerful Object/Relational Mapping (ORM) framework that simplifies the


development of Java applications to interact with the database. It’s an open-source,
lightweight, ORM tool that provides a framework for mapping object-oriented domain
models to relational databases.

Here are some of the core interfaces in Hibernate and their roles:

 SessionFactory: This is a factory class that configures Hibernate and creates session
objects. It’s immutable, thread-safe, and typically created once during application
initialization. It’s used to create Session instances1.
 Session: This interface is the main runtime interface between a Java application and
Hibernate. It allows for the creation, reading, and deletion of the entity instances.
Sessions are not thread-safe and should be created and destroyed by the application2.
 Transaction: This interface abstracts the unit of work from the application. It’s used
to manage transactions in Hibernate and provides methods for transaction
management such as begin, commit, and rollback2.
 Query: This interface allows you to perform queries against the database and retrieve
persistent objects. The Hibernate Query Language (HQL), a portable, object-oriented
extension to SQL, is used in this interface2.
 Criteria: This is a more object-oriented API for querying databases and retrieving
entities. It allows for building up a criteria query object programmatically where you
can apply filtration rules and logical conditions2.
 Configuration: This class is used to bootstrap Hibernate and allows you to configure
properties and mapping documents. It’s used at the start of the application to specify
settings related to the database and mappings1.

These interfaces are fundamental to Hibernate’s architecture, enabling a flexible and


powerful framework for persisting Java objects in a relational database.

Or

Q.5 (a) What is Hibernate? What are the features of it? 03

Hibernate is an Object/Relational Mapping (ORM) framework for Java applications. It


facilitates the management and manipulation of relational databases through an object-
oriented approach. Hibernate abstracts away much of the complexity associated with database
interactions, allowing developers to focus more on the business logic of their applications1.

Here are some key features of Hibernate:

 Database Independence: Hibernate generates database-independent queries, making


it easier to switch databases if needed2.
 Automatic Table Creation: It can automatically create necessary database tables
based on the object models2.
 Simplified Data Manipulation: Hibernate simplifies CRUD operations (Create,
Read, Update, Delete) through its session APIs2.
 Caching: It uses first-level and second-level caches to enhance performance by
reducing database access2.
 Lazy Loading: Hibernate retrieves only the data that is needed, deferring other data
fetches until required3.
 Transaction Management: It provides a transparent transaction management
abstraction layer4.
 Query Options: Hibernate supports HQL (Hibernate Query Language) and criteria
queries for retrieving objects2.

These features make Hibernate a powerful tool for developers working with Java and
relational databases, offering a blend of productivity and performance.

(b) What is OR mapping? How will you configure hibernate mapping file to map a table and its
columns from a given database?

Object-Relational Mapping (ORM) is a technique used to map object-oriented domain


models to relational databases. It bridges the gap between the object-oriented programming
paradigm and the relational database model. Hibernate, as an ORM framework, simplifies the
development of Java applications by providing a way to map Java classes to database tables
and manage the interaction between them.

To configure Hibernate mapping files for mapping a table and its columns from a given
database, follow these steps:

1. Create a Hibernate Configuration File (hibernate.cfg.xml):


o The hibernate.cfg.xml file contains configuration settings for Hibernate.
o Specify the database connection details, dialect, and other properties in this
XML file.
2. Define the Entity Class (Java POJO):
o Create a Java class that represents the entity (table) you want to map.
o Annotate the class with @Entity to indicate that it’s an entity.
o Define the properties (fields) of the entity class that correspond to the columns
in the database table.
3. Create a Hibernate Mapping File (hbm.xml):
o Create an XML file (e.g., Employee.hbm.xml) to map the entity class to the
database table.
o In the mapping file, specify the following:
 The entity name (class name).
 The table name.
 The primary key (if any).
 The mapping of each property (field) to its corresponding column in
the table.
4. Configure the Hibernate Session Factory:
o In your Java application, create a SessionFactory object using the
Configuration class.
o Load the hibernate.cfg.xml file to configure Hibernate.
o Add the mapping file (Employee.hbm.xml) to the configuration using the
addResource() method.

Example hibernate.cfg.xml for MySQL:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate
Configuration DTD 5.3//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property
name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Other properties (e.g., show_sql, hbm2ddl.auto, etc.) -->
<mapping resource="Employee.hbm.xml" /> <!-- Add your mapping file
here -->
</session-factory>
</hibernate-configuration>

Example Employee.hbm.xml (mapping file):

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
5.3//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.example.Employee" table="employee">
<id name="id" column="employee_id">
<generator class="native" />
</id>
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<!-- Other properties/columns -->
</class>
</hibernate-mapping>

In this example:

 Employee is the entity class representing the employee table.


 The mapping file (Employee.hbm.xml) specifies the mapping between the entity
properties and the table columns.

(c) What are the advantages of Spring MVC? Explain the flow of Spring Web MVC.

Spring MVC (Model-View-Controller) is a robust framework that provides a great way to


build web applications using the MVC pattern. Here are some of the advantages of using
Spring MVC:

 Separation of Concerns: It separates each role (model, view, controller) where each
can be managed by specialized objects1.
 Lightweight: Uses a lightweight servlet container for development and deployment,
making it resource-efficient1.
 Powerful Configuration: Offers robust configuration options for both framework
and application classes1.
 Rapid Development: Facilitates fast and parallel development, which is beneficial
for teams1.
 Reusable Business Code: Allows the use of existing business objects, enhancing
reusability1.
 Easy Testing: Supports JavaBeans classes, enabling easy injection of test data1.
 Flexible Mapping: Provides specific annotations for easy redirection within the
application1.

The flow of Spring Web MVC works as follows:

1. DispatcherServlet: The front controller of the Spring MVC application which


intercepts all incoming requests2.
2. Handler Mapping: The DispatcherServlet consults the handler mapping to call the
appropriate controller2.
3. Controller: Processes the request, invokes business logic, and returns a
2
ModelAndView object containing the model data and the view name .
4. View Resolver: The DispatcherServlet uses the view resolver to pick the specified
view based on the view name2.
5. View: Renders the model data and generates the HTML output that the client’s
browser can interpret2.

This flow ensures a clear separation between the application’s business logic and its
representation, providing a flexible and manageable web application structure.

You might also like