Advance Java Programming-question bank-2 Answer Key (1)
Advance Java Programming-question bank-2 Answer Key (1)
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.
Filters in Servlets are used for request preprocessing and response postprocessing.
They can be used for authentication, logging, data compression, and request modification.
@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.
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.
Example: A filter checks if a user is logged in before allowing access to protected resources.
Implementation:
((HttpServletResponse) response).sendRedirect("login.jsp");
} else {
chain.doFilter(request, response);
Prevents SQL Injection, XSS (Cross-Site Scripting), and CSRF (Cross-Site Request Forgery)
attacks.
chain.doFilter(request, response);
d) HTTPS Enforcement
Filters can cache responses for frequently requested resources like images, CSS, and JavaScript.
chain.doFilter(request, response);
res.setHeader("Content-Encoding", "gzip");
chain.doFilter(request, response);
Filters can preprocess and cache certain computations to reduce load times.
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.
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)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
<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>");
}
}
%>
<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>
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/.
@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(); }
}
3. Allows fetching results using entity names rather than table names.
- 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";
}
}
```
- 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));
}
}