Professional Documents
Culture Documents
W23 Answers For Gtu
W23 Answers For Gtu
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
// Use the socket for communication (e.g., sending and receiving data)
SQL Statement Accepts raw SQL string Uses placeholders (?) for dynamic values
Handling
Less efficient for repeated More efficient for repeated statements with
Performance
statements binding
JSP Action Tags are custom tags used to perform specific actions within JSP pages. They
extend the functionality of JSP by allowing developers to encapsulate common tasks and
improve code reusability. Here are some common action tags:
<ul>
<c:forEach var="user" items="${users.rows}">
<li>Name: ${user.name}</li>
</c:forEach>
</ul>
In this example:
<%@ taglib ... %> imports the sql tag library.
sql:query defines a query with a data source reference (jdbc/myDS) and stores the results in a
variable (users).
JSTL core tags (c:forEach) are used to iterate over the query results and display user names.
7. bean:write: This tag retrieves a property value from a JavaBean object stored in a specific
scope (e.g., request, session, application).
Java
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/bean" prefix="bean" %>
<%-- Assume a bean named "message" is available in the request scope --%>
```
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=johndoe&password=secret
```
socket.close();
}
}
Server (Java):
Java
import java.io.*;
import java.net.*;
// Close connections
clientSocket.close();
serverSocket.close();
}
Or
2(C)
Here's a JDBC program for an Employee Management application with functionalities for
inserting multiple records and displaying them in reverse order:
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 connection 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
public static void main(String[] args) {
Connection connection = null;
PreparedStatement insertStmt = null;
PreparedStatement selectStmt = null;
ResultSet rs = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open connection
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
System.err.println("Error: Class not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Error: SQLException: " + e.getMessage());
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (insertStmt != null) insertStmt.close();
if (selectStmt != null) selectStmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error: SQLException while closing resources: " + e.getMessage());
}
}
}
}
Explanation:
1. Replace placeholders like your_database_name, your_username, and your_password with your
actual database credentials.
2. The program connects to the database using the provided connection details.
3. It defines an array employeeData containing sample employee information (name, phone,
address) in a comma-separated format.
4. A PreparedStatement is used for inserting multiple records using a loop. This helps prevent
SQL injection vulnerabilities.
5. After inserting records, another PreparedStatement retrieves all employees ordered by Emp_ID
in descending order.
6. The program iterates through the results and displays employee details using ResultSet.
7. Finally, all resources (result set, statements, and connection) are closed to avoid resource
leaks.
This program demonstrates basic data insertion and retrieval using JDBC. You can extend it
to include functionalities like deleting or updating employee records by implementing
additional functionalities.
Java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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 connection 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
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open connection
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
rs = stmt.executeQuery();
if (rs.next()) {
// Login successful
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp"); // Redirect to welcome page
} else {
// Login failed
response.sendRedirect("login.jsp?error=Invalid credentials"); // Redirect to login with error
message
}
} catch (ClassNotFoundException e) {
System.err.println("Error: Class not found: " + e.getMessage());
// Handle exception (e.g., log error, display generic error message)
} catch (SQLException e) {
System.err.println("Error: SQLException: " + e.getMessage());
// Handle exception (e.g., log error, display generic error message)
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error: SQLException while closing resources: " + e.getMessage());
}
}
}
}
Explanation:
1. The servlet retrieves username and password from the login form using getParameter.
2. It connects to the database using JDBC.
3. A PreparedStatement is used to prevent SQL injection by setting parameters for the username
and password.
4. The query retrieves user data based on the provided credentials.
5. If a user is found, a session is created with the username stored as an attribute. The user is
redirected to a "welcome" page.
6. If login fails, the user is redirected back to the login page with an error message appended
to the URL (e.g., ?error=Invalid credentials).
Or
Q.3 (a) Filter Lifecycle
A filter in Java Servlet API acts as an interceptor for HTTP requests and responses. It
provides a way to pre-process requests before they reach a servlet and post-process
responses before they are sent back to the client. Filters follow a well-defined lifecycle with
three main methods:
1. init(FilterConfig filterConfig):
o This method is called once when the filter is first loaded into the web container.
o You can use this method to perform any initialization tasks, such as loading resources or
configuring the filter.
2. doFilter(ServletRequest request, ServletResponse response, FilterChain chain):
o This method is called for every request that matches the filter's mapping.
o You can examine the request and response objects, modify them if needed, and then call
chain.doFilter(request, response) to allow the request to proceed to the next filter or servlet in
the chain.
3. destroy():
o This method is called once when the filter is being removed from service.
o You can use this method to release any resources held by the filter.
Here's a visualization of the filter lifecycle:
+-------------------+
| Filter is loaded | (init)
+-------------------+
|
v
+-------------------+
| Request arrives |
+-------------------+
|
v
+-------------------+
| doFilter() called |
| (pre-processing) |
+-------------------+
|
v
+-------------------+ (chain.doFilter())
| Next filter/servlet|
+-------------------+
|
v (if next filter/servlet allows)
+-------------------+
| doFilter() called |
| (post-processing) |
+-------------------+
|
v
+-------------------+
| Response sent |
+-------------------+
|
v
+-------------------+
| Filter destroyed | (destroy)
+-------------------+
Q.3 (b) JSP vs. Servlet
Both JSP (Java Server Pages) and Servlets are Java technologies used for building web
applications, but they serve different purposes:
JSP:
Java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// If no cookie exists, create a new one and set the user name
if (userName == null) {
userName = "Guest";
Cookie cookie = new Cookie("user", userName);
cookie.setMaxAge(30 * 60); // Set cookie to expire in 30 minutes
response.addCookie(cookie);
}
Explanation:
1. The servlet checks if a cookie named "user" already exists using getCookies() and iterates
through them.
2. If the cookie is found, its value (user name) is stored in a variable.
3. If no cookie exists, a new cookie named "user" is created with the value "Guest" and a
maximum age of 30 minutes. This sets an expiry time for the cookie.
4. The servlet then generates a response welcoming the user by name (either retrieved from
the cookie or set as "Guest").
Or
faces-config.xml, JSF Standard Validator Tags, and Student Registration with JSF
<managed-bean>
<managed-bean-name>studentBean</managed-bean-name>
<managed-bean-class>com.example.StudentBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config.xml>
Q.4 (b) JSF Standard Validator Tags
JSF provides standard validator tags for common validation tasks in forms. Here are three in
detail:
1. faces-config.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<faces-config ... (refer to 4(a) for structure) ... >
<managed-bean>
<managed-bean-name>studentBean</managed-bean-name>
<managed-bean-class>com.example.StudentBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config.xml>
2. Student.java (model class):
Java
public class Student {
private int id; // Auto-generated by database
private String name;
private String email;
// Getters and setters
}
3. StudentBean.java (managed bean):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class StudentBean {
private final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // Replace with your JDBC driver class name
private final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your
connection URL
private final String USER = "your_username"; // Replace with your database username
private final String PASSWORD = "your_password"; // Replace with your database password
String sql = "INSERT INTO students (name, email) VALUES (?, ?)";
stmt = connection.prepareStatement(sql);
stmt.setString(1, student.getName());
stmt.setString(2, student.getEmail());
stmt.executeUpdate();
return "success"; // Redirect to success page (replace with your success page name)
} catch (ClassNotFoundException e) {
System.err.println("Error: Class not found: " + e.getMessage());
// Handle exception (e.g., log error, display generic error message)
return null;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
HTML, XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Student Registration</title>
</h:head>
<h:body>
<h1>Student Registration</h1>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel for="name">Name:</h:outputLabel>
<h:inputText id="name" required="true" value="#{studentBean.student.name}" />
<f:validateLength minimum="3" maximum="50" />
<h:outputLabel for="email">Email:</h:outputLabel>
<h:inputText id="email" required="true" value="#{studentBean.student.email}" />
<f:validateEmail />
</h:body>
</html>
Use code with caution.
content_copy
HTML, XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Registration Success</title>
</h:head>
<h:body>
<h1>Registration Successful!</h1>
</h:body>
</html>
Explanation:
faces-config.xml registers the StudentBean managed bean.
Student.java defines the model class for student data.
StudentBean.java handles registration logic, interacts with the database using JDBC, and
displays success messages using FacesMessage.
register.xhtml is the registration form with input fields and JSF validators.
success.xhtml (optional) is a success page displayed after successful registration.
Hibernate provides various annotations for mapping Java classes to relational database
tables and defining object-relational relationships. Here's a list of commonly used
annotations:
Spring MVC (Model-View-Controller) is a web application framework that follows the MVC
design pattern. It separates application logic into distinct layers for better organization and
maintainability:
1. Model:
Represents the data and business logic of the application.
Can include Java classes, POJOs (Plain Old Java Objects), or JPA entities.
2. View:
Responsible for presentation (the user interface).
Can be JSP pages, Thymeleaf templates, or other templating technologies.
3. Controller:
Handles incoming user requests.
Processes user input, interacts with the model to retrieve or update data, and selects the
appropriate view to render.
Additional Components:
DispatcherServlet: The central component that receives requests, dispatches them to
controllers, and forwards responses to views.
ModelAndView: An object used by controllers to specify the view to render and any data to
be passed to that view.
Benefits of Spring MVC:
Clear separation of concerns improves code reusability and maintainability.
Simplifies development by providing pre-built components for common web application
functionalities.
Offers tight integration with other Spring modules for security, data access, and more.
Here's a visual representation of Spring MVC architecture:
+-------------------+
| User | (Request)
+-------------------+
|
v
+-------------------+
| DispatcherServlet |
+-------------------+
|
v
+-------------------+ +--------------------+
| Controller | ------> | Model |
+-------------------+ +--------------------+
| ^ (Data Access)
v |
+-------------------+ +--------------------+
| ModelAndView | ------> | View |
+-------------------+ +--------------------+
| ^ (Templating)
v |
+
+-------------------+
| Response |
+-------------------+
Or
More boilerplate code for complex Less boilerplate code through object-
Boilerplate Code
queries oriented APIs