W21 Answers For Gtu
W21 Answers For Gtu
Both HTTP GET and POST methods are used to send data from a client (web browser) to a
server. However, they differ in their key characteristics:
Feature HTTP GET HTTP POST
Repeating the request with the same Repeating the request might have side
Idempotency
data should produce the same result effects (e.g., creating duplicate data)
JSP provides several implicit objects that offer pre-defined functionality within JSP pages.
Here are four commonly used ones:
1. request (ServletRequest): Represents the current HTTP request object. It allows you to
access data submitted through forms (using GET or POST), query parameters, and headers.
Java
String name = request.getParameter("username");
2. response (HttpServletResponse): Represents the current HTTP response object. It allows
you to manipulate the response sent back to the client (e.g., setting content type, headers,
or writing content).
Java
response.setContentType("text/html");
response.getWriter().println("<h1>Hello, Client!</h1>");
3. session (HttpSession): Represents the current HTTP session object. It allows you to store
and retrieve user-specific data across multiple page requests within the same session.
Java
session.setAttribute("user", userObject);
String username = (String) session.getAttribute("user");
4. application (ServletContext): Represents the ServletContext object for the web application.
It allows you to access application-wide resources and configurations.
Java
String appVersion = (String) application.getAttribute("appVersion");
Here's a Java program demonstrating how a client sends a string to the server, the server
converts it to uppercase, and sends it back:
while (true) {
Socket clientSocket = serverSocket.accept();
// Convert to uppercase
String response = message.toUpperCase();
clientSocket.close();
}
}
}
Client Code (client.java):
Java
import java.io.*;
import java.net.*;
clientSocket.close();
}
}
Explanation:
Server Side:
1. ServerSocket: Creates a ServerSocket on port 8080, waiting for incoming connections from
clients.
2. Client Connection: The server enters an infinite loop, waiting for client connections using
serverSocket.accept(). When a client connects, a new Socket object representing the client
connection is created.
3. Read Client Input: An InputStreamReader and BufferedReader are used to read the string sent
by the client from the input stream of the clientSocket.
4. Convert to Uppercase: The received message is converted to uppercase using
String.toUpperCase().
5. Send Response: A PrintWriter is used to write the uppercase response back to the client's
output stream via the clientSocket.
6. Close Connection: The clientSocket is closed after sending the response.
Client Side:
1. Socket Creation: Creates a Socket object, connecting to the server running on localhost (the
same machine) at port 8080.
2. Send String: Reads a line (the string to be converted) from the user's standard input using
System.in. Sends the string to the server using a PrintWriter.
3. Receive Response: Reads the server's response (uppercase string) from the input stream of
the clientSocket using a BufferedReader.
4. Print Response: Prints the server's response to the console.
5. Close Connection: Closes the clientSocket after receiving the response.
Running the Program:
1. Compile both server.java and client.java using a Java compiler (e.g., javac server.java client.java).
2. Run the server first: java server (This keeps the server listening for client connections).
3. In a separate terminal, run the client: java client.
4. Enter a string in the client terminal and press Enter. The server will convert it to uppercase
and send it back to the client, which will be displayed in the client terminal.
This demonstrates a basic example of client-server communication using TCP/IP sockets for
sending and receiving data in a connection-oriented manner.
Or 2(C)
Here's a JDBC program for a banking application using a bank table with the specifieyd
attributes and functionalities:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // Replace with your JDBC driver
class name
private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name"; // Replace
with your database URL
private static final String USER = "your_username"; // Replace with your database username
private static final String PASSWORD = "your_password"; // Replace with your database password
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
System.out.println("Error: JDBC driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Error: SQL exception occurred.");
e.printStackTrace();
} finally {
// Close resources
try {
if (resultSet != null) {
resultSet.close();
}
if (selectAllStatement != null) {
selectAllStatement.close();
}
if (insertStatement != null) {
insertStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.out.println("Error: Exception occurred while closing resources.");
e.printStackTrace();
}
}
}
executeUpdate(String sql):
o Specifically designed for statements that modify data (INSERT, UPDATE, DELETE).
o Returns: An integer representing the number of rows affected by the statement execution
(useful for counting inserted/updated/deleted rows).
o Throws an exception: If the statement doesn't modify data (e.g., a SELECT statement).
executeQuery(String sql):
o Executes a SELECT statement and expects to retrieve a result set containing data.
o Returns: A ResultSet object containing the results of the query.
o Throws an exception: If the statement doesn't return a result set (e.g., an INSERT, UPDATE,
or DELETE statement).
Here's a basic servlet that reads student details from a web form and stores them in a
database (replace placeholders with your actual database connection details):
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// Get student details from request parameters (assuming form uses POST method)
String name = request.getParameter("name");
String email = request.getParameter("email");
String rollNumber = request.getParameter("rollNumber"); // Assuming roll number is a string
// Database connection
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
System.out.println("Error: JDBC driver not found.");
e.printStackTrace();
// Handle error appropriately (e.g., display error message to user)
} catch (SQLException e) {
System.out.println("Error: SQL exception occurred.");
e.printStackTrace();
// Handle error appropriately (e.g., display error message to user)
} finally {
// Close resources (connection, statement)
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.out.println("Error: Exception occurred while closing resources.");
e.printStackTrace();
}
}
}
}
Explanation:
1. Annotations: Uses @WebServlet annotation to map the servlet to the URL pattern
"/StoreStudentDetails".
2. doPost Method: This servlet handles POST requests (assuming the form submits data using
POST method).
3. Get Student Details: Retrieves student name, email, and roll number from the request
parameters submitted through the form.
4. Database Connection: Establishes a connection to the database using JDBC driver and
connection details.
5. Prepared Statement: Creates a prepared statement to prevent SQL injection vulnerabilities.
6. Set Values: Sets the prepared statement parameters with the retrieved student details.
7. Execute Update: Executes the prepared statement to insert the data into the students table.
8. Send Response: Sends a success message to the user's browser.
9. Error Handling: Includes exception handling for ClassNotFoundException and SQLException to
gracefully handle potential errors.
10. Resource Closing: Ensures proper closing of connection and statement objects to avoid
resource leaks.
Or
Filters provide a centralized location to apply these functionalities across your entire
application or specific parts of it. This promotes modularity, reusability, and separation of
concerns in your web development.
A servlet's lifecycle involves several methods that get called at different stages during its
creation, initialization, and destruction:
init(ServletConfig config): Called once when the servlet is first loaded. You can use this
method to perform initialization tasks such as loading configuration data or establishing
database connections.
service(ServletRequest request, ServletResponse response): Called for every HTTP request
that matches the servlet's URL pattern. This is where the core servlet logic resides, handling
the request and generating the response.
doGet(HttpServletRequest request, HttpServletResponse response): Specifically called for
GET requests.
doPost(HttpServletRequest request, HttpServletResponse response): Specifically called for
POST requests. (You can have similar methods for other HTTP methods like PUT, DELETE,
etc.)
destroy(): Called once when the servlet is about to be unloaded from memory. You can use
this method to clean up resources, such as closing database connections.
The web container (e.g., Tomcat, Jetty) manages the lifecycle of servlets within a web
application. It's responsible for:
Loading servlets based on their definitions in the deployment descriptor (web.xml).
Creating servlet instances.
Calling the appropriate lifecycle methods (init(), service(), etc.) at the right times.
Providing them with resources like ServletConfig and ServletContext.
Handling servlet communication with the client (web browser) by processing requests and
sending responses.
Q.3 (c) Request Dispatcher and Its Methods
Request Dispatcher: An interface provided by the Java Servlet API that allows servlets and
JSPs to forward requests or include content from other resources within the same web
application.
Differences Between forward() and include():
forward():
o Redirects the request to another resource (servlet or JSP) within the web application.
o The client browser doesn't know about the forwarding. The URL in the browser's address
bar remains the same as the original request.
o Any request parameters or attributes from the original request are not automatically
available in the forwarded resource unless explicitly passed.
include():
o Includes the content from another resource (servlet or JSP) within the current response.
o The included content is merged into the current response.
o The client browser doesn't receive a separate request for the included resource.
o Request parameters and attributes from the original request are available in the included
resource.
Example Program:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Q.4 (a) Difference Between Include Directive and jsp:include Action Tag
Both the include directive (<%@ include file="..." %>) and the jsp:include action tag allow you to
include content from another JSP file within the current JSP. However, they differ in key
aspects:
File Path Absolute path or relative path Relative path within the current JSP's
Requirement within web application directory only
Can pass attributes to the included file
Attribute Support No
using var and flush
<ui:insert name="content">
</ui:insert>
<footer>
Copyright © 2024
</footer>
</body>
</html>
page.xhtml: (Uses the template and inserts components)
HTML, XML
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib prefix="ui" uri="http://java.sun.com/jsf/facelets" %>
<ui:composition template="/template.xhtml">
<ui:define name="content">
<h:outputText value="Welcome to the page!" />
</ui:define>
</ui:composition>
JSF provides standard converter tags for converting user input from String format to specific
data types used by JSF components. Here are three examples:
1. f:convertNumber: Converts user input to a numeric type (e.g., Integer, Double) based on
attributes like type and locale.
HTML, XML
<h:inputText value="#{bean.age}" converter="f:convertNumber" type="integer" />
2. f:convertDateTime: Converts user input to a date/time object based on attributes like
pattern, locale, and timeZone.
HTML, XML
<h:inputText value="#{bean.dob}" converter="f:convertDateTime" pattern="yyyy-MM-dd" />
3. f:convertBoolean: Converts user input (e.g., checkbox value "on" or "off") to a boolean
value.
HTML, XML
<h:selectBooleanCheckbox value="#{bean.subscribed}" converter="f:convertBoolean" />
These converter tags help ensure that JSF components receive data in the expected format
and avoid potential errors or unexpected behavior.
Q.4 (c) JSP Login Module with Reset Password (Database Example)
This example demonstrates a basic login module with a reset password feature using JSP
and JDBC. However, it's important to note that implementing secure login and password
reset mechanisms requires additional security practices like password hashing and salting:
Java
if (email != null && pwd != null) {
// Prepare statement to check user credentials
String sql = "SELECT * FROM users WHERE email = ? AND password = ?";
stmt = connection.prepareStatement(sql);
stmt.setString(1, email);
stmt.setString(2, pwd); // **Security Risk: Don't store passwords in plain text!**
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// Login successful - redirect to a welcome page or dashboard
session.setAttribute("user", email); // Set session attribute for user identification
response.sendRedirect("welcome.jsp");
return;
} else {
message = "Invalid email or password.";
}
}
} catch (SQLException e) {
e.printStackTrace();
message = "Error: Database connection failed.";
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} %>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="" method="post">
<label for="email">Email:</label>
<input type="text" name="email" id="email" required><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br>
<input type="submit" value="Login">
</form>
<% if (!message.isEmpty()) { %>
<p style="color: red;"><%= message %></p>
<% } %>
<a href="reset_password.jsp">Forgot password?</a>
</body>
</html>
reset_password.jsp: (Reset password form)
Java
<%@ page import="java.sql.*" %>
<%-- Replace with your database connection details --%>
<% String jdbcDriver = "com.mysql.cj.jdbc.Driver";
String dbURL = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password"; %>
<%! Connection connection = null;
PreparedStatement stmt = null;
String message = ""; %>
<% try {
Class.forName(jdbcDriver);
connection = DriverManager.getConnection(dbURL, username, password);
if (rowsUpdated > 0) {
message = "Password reset successfully!";
} else {
message = "Error: No user found with that email.";
}
}
} catch (SQLException e) {
e.printStackTrace();
message = "Error: Database connection failed.";
} finally {
try {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} %>
<!DOCTYPE html>
<html>
<head>
<title>Reset Password</title>
</head>
<body>
<h1>Reset Password</h1>
<form action="" method="post">
<label for="email">Email:</label>
<input type="text" name="email" id="email" required><br>
<label for="new_password">New Password:</label>
<input type="password" name="new_password" id="new_password" required><br>
<input type="submit" value="Reset Password">
</form>
<% if (!message.isEmpty()) { %>
<p><%= message %></p>
<% } %>
<a href="login.jsp">Back to LoginJava
</a>
</body>
</html>
welcome.jsp: (Welcome page after successful login)
Java
<%@ page import="java.io.IOException" %>
<% String user = (String) session.getAttribute("user");
if (user == null) {
response.sendRedirect("login.jsp"); // Redirect to login if no user in session
return;
}
%>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= user %>!</h1>
<p>You are successfully logged in.</p>
<a href="logout.jsp">Logout</a>
</body>
</html>
logout.jsp: (Logout page)
Java
<%@ page import="java.io.IOException" %>
<% session.invalidate(); // Invalidate session to log out
response.sendRedirect("login.jsp"); %>
Q.5 (a) Dependency Injection Explained
Dependency Injection (DI) is a design pattern that promotes loose coupling between
objects. It focuses on providing an object with its dependencies (other objects it needs to
function) rather than creating them itself. This approach offers several benefits:
Benefits:
Testability: Easier to write unit tests by injecting mock dependencies.
Maintainability: Code becomes more modular and easier to modify.
Flexibility: Allows swapping out dependencies based on context.
Decoupling: Objects rely less on specific implementations of their dependencies.
Dependency Injection Techniques:
Constructor Injection: Dependencies are passed as arguments to the object's constructor.
Setter Injection: Dependencies are injected using setter methods within the object.
Interface Injection: Objects depend on interfaces, allowing for different implementations.
Example (Constructor Injection):
Java
public class UserService {
More portable across different database Less portable, may require vendor-
Portability
vendors specific code
Type
Supports type safety (less error-prone) Doesn't enforce type safety
Safety
Offers some protection against SQL Requires careful parameter binding for
Security
injection security
1. Configuration: Defines how Hibernate interacts with the database, including connection
details, dialect, and mapping information.
2. SessionFactory: A factory-like object responsible for creating Session objects used for
interacting with the database.
3. Session: Provides a unit of work for database operations. It manages transactions and
provides methods for saving, loading, updating, and deleting data.
4. Criteria API: An object-oriented API for constructing complex queries using criteria builders.
5. HQL (Hibernate Query Language): An object-oriented query language for interacting with
the database using Java-like syntax.
6. Persistence API: (JPA) Provides a standard interface for persistence providers like Hibernate.
7. Mapping Files (hbm.xml): (Optional) Configuration files that define mappings between Java
classes and database tables. Can be replaced by annotations in JPA.
Benefits of Hibernate:
Abstraction: Hides the complexities of JDBC and SQL, allowing developers to work with
objects.
Object-Relational Mapping: Simplifies the persistence layer with automatic data
conversion.
Reduced Code: Less boilerplate code compared to JDBC and raw SQL.
Querying: Offers HQL and Criteria API for flexible object-oriented querying.
Transaction Management: Provides support for managing database transactions.
Or