S23 Answers For Gtu
S23 Answers For Gtu
// Close resources
resultSet.close();
connection.close();
}
}
Q.1 (b) Implement the client-server program using UDP Sockets. Client will request to
download the file from server and server will send it in chunks. (4 marks)
Server (server.java):
Java
import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
while (true) {
// Receive a request packet from the client
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
if (request.equals("download")) {
// Open the file
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
int bytesRead;
int totalSent = 0;
long fileSize = file.length();
totalSent += bytesRead;
System.out.println("Sent chunk: " + totalSent + "/" + fileSize);
}
fileInputStream.close();
}
}
serverSocket.close();
}
}
Client (client.java):
Java
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
fileOutputStream.write(buffer, 0, bytesReceived);
}
fileOutputStream.close();
clientSocket.close();
}
}
Q.1 (c) What do you mean by session tracking? Discuss different session tracking
techniques. (7 marks)
Session Tracking:
In web applications, session tracking allows the server to maintain information about a
specific user's interaction across multiple HTTP requests. This is essential for tasks like
maintaining login status, shopping carts, or personal preferences between page visits.
Q.2 (c) Demonstrate the use of ServletRequestDispatcher and its methods include and
forward (7 marks)
ServletRequestDispatcher is an interface in the Java Servlet API that facilitates forwarding
requests within a web application. It allows a servlet to delegate further processing or
generate a response by including content from another resource or forwarding the request
to another servlet.
Include and Forward Methods:
1. include(ServletRequest request, ServletResponse response):
Includes the content of another resource (servlet, JSP, HTML file) within the current
response.
Control is returned to the calling servlet after the included resource is processed.
The included content is merged into the current response.
Example:
Java
public class MainServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Welcome!</h1>");
Or
Here's a demonstration of using JSP action tags include and forward:
include tag:
Java
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
Explanation:
The jsp:include tag is used to include the content of another JSP file (header.jsp) within this
main page.
The included content is inserted at the location of the jsp:include tag.
The main page's processing continues after the included content is processed.
header.jsp:
Java
<header>
<h2>This is the included header content!</h2>
</header>
Explanation:
This JSP file contains the header content that will be included in the main page.
forward tag:
Java
<!DOCTYPE html>
<html>
<head>
<title>Redirect to another page</title>
</head>
<body>
<h1>Initial content</h1>
</body>
</html>
Explanation:
The jsp:forward tag redirects the request to another JSP (processing.jsp) for further processing.
Control is transferred to the forwarded JSP, and its output becomes the final response sent
to the client.
Any content after the jsp:forward tag in the original JSP is not executed or included in the
response.
processing.jsp:
Java
<!DOCTYPE html>
<html>
<head>
<title>Processing Page</title>
</head>
<body>
<h1>Processing completed!</h1>
</body>
</html>
Explanation:
This JSP receives the forwarded request and generates the final response content.
The client will only see the content of processing.jsp, as the request was forwarded.
Choosing Between include and forward:
Use include when you want to incorporate content from another JSP while maintaining
control flow in the current page.
Use forward when you want to delegate the entire request to another JSP for processing and
generate a single, unified response to the client.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
String query = "INSERT INTO students (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.close();
connection.close();
}
}
Explanation:
This code demonstrates using PreparedStatement to insert data into a database table.
Prepared statements prevent SQL injection vulnerabilities as parameters are separated from
the SQL query.
You set values for parameters using methods like setString and setInt based on their data
types.
XML
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>MyServlet</servlet-name>
</filter-mapping>
public Student() {
}
</body>
</html>
Explanation:
jsp:useBean creates a bean instance (student) of type Student with session scope.
jsp:setProperty sets the bean's properties (name and age) with specified values.
3. JSP to Display Properties (displayStudent.jsp):
Java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Display Student Details</title>
</head>
<body>
</body>
</html>
Explanation:
jsp:useBean retrieves the existing bean instance (student) from the session scope.
jsp:getProperty retrieves the values of the bean's properties (name and age) and displays them
on the page.
This example demonstrates how to use the jsp:useBean tag to create, initialize, and access a
Java Bean within your JSP pages.
Q.3 (a) What is FilterConfig? How will you use it? (3 marks)
FilterConfig:
FilterConfig is an interface provided by the Java Servlet API that provides configuration
information to a filter instance.
It allows filters to access initialization parameters defined in the deployment descriptor
(web.xml) or passed programmatically.
Using FilterConfig:
1. Obtain the FilterConfig object:
o A filter instance receives the FilterConfig object when its init() method is called.
Java
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
2. Access initialization parameters:
o Use the getInitParameter(String name) method of FilterConfig to retrieve configuration values
defined in the deployment descriptor or programmatically set.
Java
String dbUsername = config.getInitParameter("dbUsername");
String dbPassword = config.getInitParameter("dbPassword");
Q.3 (b) Write a code snippet to explain the use of CallableStatement (3 marks)
CallableStatement:
CallableStatement is an interface in the JDBC API that extends PreparedStatement and allows the
execution of stored procedures, which are pre-compiled SQL statements on the database
server.
It allows you to have both input and output parameters in database procedures.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
statement.close();
connection.close();
}
}
Explanation:
This code demonstrates calling a stored procedure named register_user that takes three input
parameters (name, email, contact number).
CallableStatement is used to set the input parameters and execute the procedure.
The execute() method returns true if the procedure returns a result set.
Or
Q.3 (c) JSP Web Application for User Registration and Listing (7 marks)
1. HTML Form (register.html):
HTML
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>Register User</h1>
<form action="register.jsp" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="contact">Contact Number:</label>
<input type="text" id="contact" name="contact" required><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
2. Registration JSP (register.jsp):
Java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-Java
8"%>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String contact = request.getParameter("contact");
try {
// Replace with your actual database connection details
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database",
"your_username", "your_password");
String sql = "INSERT INTO users (name, email, contact) VALUES (?, ?, ?)";
statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, email);
statement.setString(3, contact);
if (rowsAffected > 0) {
out.println("User registration successful!");
} else {
out.println("Error registering user. Please try again.");
}
} catch (Exception e) {
e.printStackTrace();
out.println("An error occurred during registration: " + e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
%>
3. User List JSP (listUsers.jsp):
Java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Registered Users</title>
</head>
<body>
<h1>Registered Users</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<%
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// Replace with your actual database connection details
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database",
"your_username", "your_password");
resultSet = statement.executeQuery();
while (resultSet.next()) {
String userName = resultSet.getString("name");
String userEmail = resultSet.getString("email");
String userContact = resultSet.getString("contact");
%>
<tr>
<td><%= userName %></td>
<td><%= userEmail %></td>
<td><%= userContact %></td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
out.println("Error retrieving user list: " + e.getMessage());
} finally {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
%>
</table>
</body>
</html>
Explanation:
register.html: This HTML form collects user registration details (name, email, contact).
register.jsp:
o Retrieves user data from the submitted form.
o Establishes a database connection.
o Prepares a PreparedStatement to insert the user data into the users table.
o Executes the statement and checks for successful insertion.
o Provides feedback to the user based on the outcome.
listUsers.jsp:
o Establishes a database connection.
o Prepares a PreparedStatement to select all users from the users table.
o Executes the query and iterates through the result set.
o Displays user details (name, email, contact) in a table format.
o Handles potential exceptions and displays error messages if necessary.
A custom tag allows you to encapsulate reusable functionality within your JSP pages. Here's
a tag to print the current date and time:
currentTimeTag.tag:
Java
<%@ tag language="java" pageEncoding="UTF-8" %>
<%@ tag taglib uri="mytaglib" prefix="ct" %>
**currentTimeTag.tagfile:**
```java
<%@ include file="WEB-INF/tld/currentTimeTag.tld" %>
<%@ tag import="java.text.SimpleDateFormat" %>
<%@ tag class="com.example.CurrentTimeTagHandler" %>
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println(formatter.format(new Date()));
}
}
currentTimeTag.tld:
XML
<taglib
uri="mytaglib"
tagclass="com.example.currentTimeTag.currentTimeTagHandler" >
</taglib>
Explanation:
We define a custom tag library (mytaglib) and its tag class (CurrentTimeTagHandler).
The tag handler retrieves the current date and formats it using SimpleDateFormat.
The TLD file (currentTimeTag.tld) maps the tag name (currentTime) to the tag class.
The JSF request processing life cycle is a well-defined set of phases that JSF applications go
through to handle user requests. Here's a detailed breakdown of each phase and its
significance:
1. Restore View (Restore View Phase):
If the user has previously interacted with the application and a session exists, JSF attempts
to restore the view state from the previous request.
The view state is a serialized representation of the JSF components and their current values.
Restoring the view state allows JSF to maintain application state across user interactions.
2. Process Faces Events (Apply Request Values Phase):
JSF processes events triggered by user interactions (e.g., button clicks, form submissions)
from the submitted request.
Events are typically associated with JSF components and carry information about the user
action.
In this phase, JSF updates the component tree with data from the request parameters,
applying appropriate type conversions.
3. Apply Validators (Process Validations Phase):
JSF validators associated with individual components or the entire form are invoked to
validate user input.
Validators can be defined declaratively within JSF pages or programmatically in managed
beans.
If validation fails, JSF displays error messages to the user and prevents further processing.
4. Update Model Values (Update Model Values Phase):
Validated user input is converted to appropriate model objects.
JSF utilizes converters registered for specific data types to ensure data consistency between
UI components and underlying models.
Model objects typically represent the business logic and data of your application.
5. Invoke Application Logic (Invoke Application Phase):
Managed beans associated with the view are instantiated or retrieved from the request or
session scope.
Managed beans can handle application logic using the updated model values and interact
with backing services like databases or external APIs.
This phase allows developers to implement business logic and data manipulation within the
JSF framework.
6. Render Response (Render Response Phase):
The appropriate JSF view (*.xhtml) is rendered based on the current model state.
JSF components are rendered based on their associated component classes and attributes
defined in the view.
The rendered view is sent to the client's web browser.
Key Points:
Each phase offers extension points through JSF lifecycle listeners for custom behavior.
Understanding this life cycle is crucial for creating well-structured and efficient JSF
applications.
JSF provides built-in navigation mechanisms to navigate between different JSF views.
JSF offers a declarative development approach, promoting separation of concerns and
reducing the need for complex JSP code.
Or
<head>
<title>JSF Action Event Example</title>
</head>
<body>
<f:view>
<h1 id="message"></h1>
<button type="button" ui:command="#{myBean.greet}">Greet</button>
</f:view>
</body>
</html>
MyBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class MyBean {
ColorConverter.java:
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) throws
ConverterException {
if (value != null && !value.isEmpty()) {
try {
return Color.valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
throw new ConverterException("Invalid color entered: " + value);
}
}
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) throws
ConverterException {
if (value instanceof Color) {
return ((Color) value).name().toLowerCase();
}
return null;
}
}
index.xhtml:
XML
<f:view>
<h:selectOneMenu converter="colorConverter">
<f:selectItem itemValue="RED" itemLabel="Red" />
<f:selectItem itemValue="GREEN" itemLabel="Green" />
<f:selectItem itemValue="BLUE" itemLabel="Blue" />
</h:selectOneMenu>
</f:view>
<f:metadata>
<f:converter id="colorConverter" converterClass="com.example.ColorConverter" />
</f:metadata>
Explanation:
The ColorConverter class implements the Converter interface and defines methods for
converting between Color objects and their string representations.
The index.xhtml page defines a dropdown using h:selectOneMenu and associates the custom
converter with the converter attribute.
The converter ensures that the selected color value is correctly converted to a Color object
when submitted and vice versa.
The JSTL (JavaServer Pages Standard Tag Library) SQL tag library provides tags for executing
SQL queries and manipulating database data directly within JSP pages. Here's a discussion of
the main tags provided by the JSTL SQL tag library:
1. **<sql:setDataSource>**:
- This tag is used to establish a connection to the database by specifying the JNDI name of
the DataSource.
- It sets the DataSource object as a page context attribute, making it available for use by
other SQL tags.
- Example:
```jsp
```
2. **<sql:query>**:
- This tag is used to execute SQL queries against the database.
- It requires the 'dataSource' attribute to specify the DataSource to use for the query.
- The query result is stored in a ResultSet object, which can be iterated over using other
JSTL tags like <c:forEach>.
- Example:
```jsp
</sql:query>
```
3. **<sql:update>**:
- This tag is used to execute SQL update statements (e.g., INSERT, UPDATE, DELETE)
against the database.
- It requires the 'dataSource' attribute to specify the DataSource to use for the update.
- Example:
```jsp
<sql:update dataSource="${myDataSource}">
</sql:update>
```
4. **<sql:param>**:
- This tag is used to set parameters for SQL queries or updates.
- It is nested within <sql:query> or <sql:update> tags and provides parameter values for
placeholders in the SQL statement.
- Example:
```jsp
<sql:update dataSource="${myDataSource}">
<sql:param value="john_doe"/>
<sql:param value="[email protected]"/>
</sql:update>
```
5. **<sql:transaction>**:
- This tag is used to group multiple SQL operations into a single transaction.
- It requires the 'dataSource' attribute to specify the DataSource to use for the transaction.
- It ensures that either all SQL operations within the transaction are successfully executed,
or none of them are.
- Example:
```jsp
<sql:transaction dataSource="${myDataSource}">
<sql:update>
</sql:update>
<sql:update>
</sql:update>
</sql:transaction>
```
<sql:batch>: While not mentioned in the initial list, the <sql:batch> tag is also part of the JSTL SQL tag
library. It allows for batch processing of multiple SQL commands as a single unit, which can improve
performance for bulk updates1
7. **<sql:param>**:
- It is nested within <sql:query> or <sql:update> tags and provides parameter values for
placeholders in the SQL statement.
- Example:
```jsp
<sql:update dataSource="${myDataSource}">
<sql:param value="john_doe"/>
<sql:param value="[email protected]"/>
</sql:update>
```
- Example:
```jsp
<sql:transaction dataSource="${myDataSource}">
</sql:query>
</sql:transaction>
```
These tags provided by the JSTL SQL tag library allow developers to interact with databases
directly within JSP pages, providing a convenient way to perform database operations
without writing Java code.
Or
ORM bridges the gap between object-oriented programming in Java and the relational
model of databases. It allows you to define how your Java classes (entities) correspond to
database tables and their columns.
<hibernate-mapping>
<class name="com.example.User" table="users">
<id name="id" column="user_id" type="long">
<generator class="increment" />
</id>
<property name="username" column="username" type="string" />
<property name="email" column="email" type="string" />
</class>
</hibernate-mapping>
Explanation:
This file defines an entity class User mapped to the database table users.
The id property is mapped to the user_id column using the long type and an increment
generator for auto-generated IDs.
Other properties (username, email) are mapped to their respective columns with appropriate
data types.