0% found this document useful (0 votes)
15 views

Advance Java Programming-question bank-2 Answer Key (1)

The document is a question bank covering various topics in Advance Java Programming, including JDBC, Servlets, JSP, Hibernate, Spring, and web application development. It explains key concepts such as ResultSetMetaData, ServletContext, Criteria API, and the use of filters for security and performance. Additionally, it provides code examples for servlets, JSP applications, and Spring Boot applications to illustrate these concepts.

Uploaded by

binitn845
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Advance Java Programming-question bank-2 Answer Key (1)

The document is a question bank covering various topics in Advance Java Programming, including JDBC, Servlets, JSP, Hibernate, Spring, and web application development. It explains key concepts such as ResultSetMetaData, ServletContext, Criteria API, and the use of filters for security and performance. Additionally, it provides code examples for servlets, JSP applications, and Spring Boot applications to illustrate these concepts.

Uploaded by

binitn845
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Advance Java Programming

Question Bank-2
Explain the importance of ResultSetMetaData in JDBC.
1
Provides metadata about a ResultSet, such as column count, types, and names.
What is the role of ServletContext and ServletConfig in Java EE applications?
2
ServletContext provides global configuration across all servlets, while ServletConfig allows individual
servlet configuration.
Explain the purpose of Criteria API in Hibernate.
3
Criteria API provides a programmatic way to query databases using Hibernate, offering dynamic and type-
safe queries.
What are Hibernate Annotations and why are they useful?
4
Annotations like @Entity, @Table, @Column simplify ORM mappings.
Define Aspect-Oriented Programming in Spring.
5
Separates cross-cutting concerns using @Aspect, @Before, @After.
Write a Servlet program to handle form submission and process user input.

A Servlet that handles form submission and processes user input:


java
CopyEdit
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
6
@WebServlet("/FormServlet")
public class FormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.setContentType("text/html");
response.getWriter().println("<h1>Welcome, " + name + "!</h1>");
}
}
This servlet retrieves the name parameter from the form and displays a welcome message.
Explain the role of filters in Servlets with an example.

 Filters in Servlets are used for request preprocessing and response postprocessing.

 They can be used for authentication, logging, data compression, and request modification.

Example of a logging filter:


java
CopyEdit
import java.io.IOException;
import javax.servlet.*;
7 import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter("/*")
public class LoggingFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("Request to: " + req.getRequestURI());
chain.doFilter(request, response);
}
}
This filter logs all incoming requests before passing them to the servlet.
Develop a JSP application that uses session management to maintain user login.

A JSP page that manages user sessions and maintains login state:
jsp
CopyEdit
<%@ page session="true" %>
<html>
<body>
<%
String user = (String) session.getAttribute("username");
8
if (user == null) {
user = request.getParameter("username");
if (user != null) {
session.setAttribute("username", user);
out.println("<h2>Welcome, " + user + "!</h2>");
} else {
out.println("<h2>Please log in.</h2>");
}
} else {
out.println("<h2>Welcome back, " + user + "!</h2
Write a Servlet program to handle user authentication.

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
9 String password = request.getParameter("password");
if ("admin".equals(username) && "password".equals(password)) {
response.getWriter().println("Login successful");
} else {
response.getWriter().println("Invalid credentials");
}
}
}
Explain how Servlet filters are used to enhance security and performance.

 Filters intercept requests and responses for logging, authentication, and compression.

 Example: Logging requests in a filter before reaching the servlet.

Servlet Filters for Security and Performance Enhancement

Servlet Filters are components in Java EE web applications that intercept HTTP requests and responses
before they reach the servlet or after they leave it. They help in modifying or processing the
request/response in a structured manner, thereby improving security and performance.

10 1. Enhancing Security with Servlet Filters

a) Authentication and Authorization

Filters can verify user credentials before forwarding requests to servlets.

Example: A filter checks if a user is logged in before allowing access to protected resources.

Implementation:

public class AuthenticationFilter implements Filter {

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

throws IOException, ServletException {


HttpServletRequest req = (HttpServletRequest) request;

HttpSession session = req.getSession(false);

if (session == null || session.getAttribute("user") == null) {

((HttpServletResponse) response).sendRedirect("login.jsp");

} else {

chain.doFilter(request, response);

b) Input Validation and Sanitization

Prevents SQL Injection, XSS (Cross-Site Scripting), and CSRF (Cross-Site Request Forgery)
attacks.

Filters can sanitize input data before reaching the servlet.

Example: Removing special characters to prevent SQL injection.

c) Logging and Auditing

Filters can log all incoming requests for security auditing.

Helps in detecting malicious activity or analyzing system usage.

Example: Logging user IP addresses and accessed resources.

public class LoggingFilter implements Filter {

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

throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;

System.out.println("Request from IP: " + req.getRemoteAddr() + " to " + req.getRequestURI());

chain.doFilter(request, response);

d) HTTPS Enforcement

Ensures that all requests are served over HTTPS.

Redirects HTTP requests to HTTPS for secure communication.

2. Enhancing Performance with Servlet Filters

a) Caching Static Content

Filters can cache responses for frequently requested resources like images, CSS, and JavaScript.

Reduces processing load on the server and improves response time.

Example: Setting cache headers:

public class CachingFilter implements Filter {

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


throws IOException, ServletException {

HttpServletResponse res = (HttpServletResponse) response;

res.setHeader("Cache-Control", "public, max-age=3600");

chain.doFilter(request, response);

b) Compression (Gzip Filter)

Reduces response size using Gzip compression, improving load times.

Example: Applying Gzip compression:

public class GzipFilter implements Filter {

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

throws IOException, ServletException {

HttpServletResponse res = (HttpServletResponse) response;

res.setHeader("Content-Encoding", "gzip");

chain.doFilter(request, response);

c) Request Throttling (Rate Limiting)

Prevents excessive requests from overwhelming the server (DDoS mitigation).

Example: Limiting requests from a single IP within a timeframe.

d) Lazy Loading and Preprocessing

Filters can preprocess and cache certain computations to reduce load times.

Example: Preloading frequently used database queries.

Conclusion

Servlet filters play a crucial role in securing web applications by authenticating users,
preventing attacks, enforcing HTTPS, and logging activities. They also enhance performance by
caching, compressing responses, and throttling excessive requests. Properly designed filters
improve both security and efficiency in Java EE applications.

Design a JSP-based dynamic web page that interacts with a database.

Here’s a JSP-based dynamic web page that interacts with a MySQL database. The page will
allow users to view and add records to a database table named users containing id, name, and
email.

11 1. Project Structure
JSP-DatabaseApp/
│── WebContent/
│ ├── index.jsp
│ ├── addUser.jsp
│ ├── viewUsers.jsp
│── WEB-INF/
│ ├── web.xml
│── src/
│ ├── db/
│ │ ├── DBConnection.java
│── lib/ (contains MySQL JDBC driver)
│── build.gradle (if using Gradle)

2. Database Setup (MySQL)


CREATE DATABASE userdb;
USE userdb;

CREATE TABLE users (


id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);

3. Database Connection Class (DBConnection.java)


This Java class manages the database connection.
package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


private static final String URL = "jdbc:mysql://localhost:3306/userdb";
private static final String USER = "root"; // Change as needed
private static final String PASSWORD = ""; // Change as needed

public static Connection getConnection() throws SQLException, ClassNotFoundException {


Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}

4. index.jsp (Main Page with Links)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<html>
<head>
<title>User Management</title>
</head>
<body>
<h2>Welcome to User Management</h2>
<a href="viewUsers.jsp">View Users</a> | <a href="addUser.jsp">Add User</a>
</body>
</html>

5. addUser.jsp (Form to Add Users)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<%@ page import="java.sql.*" %>
<%@ page import="db.DBConnection" %>

<html>
<head>
<title>Add User</title>
</head>
<body>
<h2>Add a New User</h2>
<form method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Add User">
</form>

<%
if(request.getMethod().equals("POST")) {
String name = request.getParameter("name");
String email = request.getParameter("email");

try {
Connection conn = DBConnection.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO users (name, email)
VALUES (?, ?)");
ps.setString(1, name);
ps.setString(2, email);
ps.executeUpdate();
conn.close();
out.println("<p>User added successfully!</p>");
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
%>

<br><a href="index.jsp">Back to Home</a>


</body>
</html>

6. viewUsers.jsp (Displays Users from Database)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<%@ page import="java.sql.*" %>
<%@ page import="db.DBConnection" %>

<html>
<head>
<title>View Users</title>
</head>
<body>
<h2>List of Users</h2>

<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>

<%
try {
Connection conn = DBConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
</tr>
<%
}
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
%>
</table>

<br><a href="index.jsp">Back to Home</a>


</body>
</html>

7. web.xml (Servlet Configuration)


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

8. Steps to Deploy
1. Install MySQL and create the userdb database with the users table.
2. Add MySQL JDBC Driver (mysql-connector-java.jar) to the lib/ folder or
dependency in pom.xml (Maven) or build.gradle (Gradle).
3. Run Apache Tomcat and deploy the project.
4. Access http://localhost:8080/JSP-DatabaseApp/.

Write a Spring Boot application to demonstrate dependency injection.

@Component
public class MyService {
public String getMessage() { return "Hello from Service"; }
}
12 @RestController
public class MyController {
@Autowired MyService service;
@GetMapping("/")
public String home() { return service.getMessage(); }
}

Explain Hibernate Query Language (HQL) with examples.

o Hibernate Query Language (HQL) is an object-oriented query language similar to


SQL but designed for Hibernate.

o It operates on persistent objects instead of database tables.


13 o Advantages of HQL:

1. Database-independent, as it works on entity objects.

2. Supports polymorphic queries.

3. Allows fetching results using entity names rather than table names.

Design a Spring MVC application for an online book store.


14
Components of Spring MVC for an Online Book Store:
1. Model: Represents book data.
2. Controller: Handles user requests.
3. View: Displays book details.

- Book Entity Class:


```java
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
// Getters and Setters
}
```

- Spring Repository Interface:


```java
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
```

- Spring Service Layer:


```java
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> getAllBooks() { return bookRepository.findAll(); }
}
```

- Spring Controller:
```java
@Controller
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public String listBooks(Model model) {
model.addAttribute("books", bookService.getAllBooks());
return "booklist";
}
}
```

- JSP View (`booklist.jsp`):


```jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h2>Online Book Store</h2>
<table border="1">
<tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th></tr>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.id}</td>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.price}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
```

- Explanation:
- The Book Entity represents book data stored in a database.
- The Book Repository provides CRUD operations.
- The Book Service retrieves book data.
- The Book Controller handles HTTP requests and returns book data to the view.
- The JSP View displays a list of books dynamically.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```

- User Controller:
```java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/register")
public ResponseEntity<User> registerUser(@RequestBody User user) {
return ResponseEntity.ok(userRepository.save(user));
}
}

You might also like