3 Java
3 Java
user authentication, a simple counter, factorial calculation, form processing, and simulated database
interactions for product listings and employee records. Each example includes the necessary Java or JSP
code, along with explanations and expected behavior.
**Note on Execution:**
To run these examples, you will need a Java Development Kit (JDK) and a Servlet/JSP container like
Apache Tomcat.
1. **For Servlets:** Compile the `.java` files into `.class` files and place them in the `WEB-INF/classes`
directory of your web application. Configure `web.xml` as shown for each servlet.
2. **For JSPs:** Place the `.jsp` files directly in your web application's root directory or a subdirectory.
4. Access the URLs as specified for each example in your web browser.
---
This servlet handles a POST request, validates the provided username and password against a
predefined set, and returns a success or error message.
**`LoginServlet.java`**
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
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
super.init();
users.put("admin", "password123");
users.put("user", "userpass");
users.put("test", "test1234");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Login Result</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Login Successful!</h1>");
} else {
out.println("<h1>Login Failed!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h1>User Login</h1>
<label for="username">Username:</label><br>
<label for="password">Password:</label><br>
</form>
</body>
</html>
```
**Expected Output:**
* If you access `loginForm.html`, enter `admin` and `password123`, and submit, you will see "Login
Successful! Welcome, admin!".
* For any other credentials, you will see "Login Failed! Invalid username or password.".
---
This servlet increments and displays a counter each time it is accessed. The counter is stored as a
`ServletContext` attribute, making it application-wide.
**`CounterServlet.java`**
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CounterServlet")
response.setContentType("text/html");
if (count == null) {
count = 1;
} else {
count++;
context.setAttribute("visitCount", count);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Page Counter</title>");
out.println("</head>");
out.println("<body>");
out.println("</body>");
out.println("</html>");
out.close();
```
**Expected Output:**
---
This servlet receives a GET request with a number, computes its factorial, and returns the result.
**`FactorialServlet.java`**
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FactorialServlet")
response.setContentType("text/html");
long result = 0;
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Factorial Result</title>");
out.println("</head>");
out.println("<body>");
} else {
try {
int number = Integer.parseInt(numberStr);
if (number < 0) {
} else if (number > 20) { // Factorial grows very fast, long might overflow
message = "Number is too large for factorial calculation (max 20 for long).";
else {
result = calculateFactorial(number);
} catch (NumberFormatException e) {
out.println("</body>");
out.println("</html>");
out.close();
if (n == 0 || n == 1) {
return 1;
}
long fact = 1;
fact *= i;
return fact;
```
**Expected Output:**
---
This JSP page displays a form and, upon submission, retrieves the entered name and email to display a
welcome message.
**`welcomeForm.jsp`**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Form</title>
</head>
<body>
<%
%>
<%
} else {
%>
<label for="userName">Name:</label><br>
</form>
<%
%>
</body>
</html>
```
**Expected Output:**
* Initially, you will see a form asking for Name and Email.
* After filling the form and submitting, the page will refresh and display "Welcome, [Your Name]!" and
"Your email address is: [Your Email]".
---
### 5. JSP Page: Product List and Shopping Cart (Simulated Database)
This example simulates fetching products from a database (using an `ArrayList` for simplicity) and allows
users to "add" them to a shopping cart (using session).
```java
package com.example.model; // Adjust package as needed
this.id = id;
this.name = name;
this.price = price;
// Getters
```
**`products.jsp`**
```jsp
<%@ page import="com.example.model.Product" %> <%-- Adjust package if you changed it --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product Catalog</title>
<style>
th { background-color: #f2f2f2; }
.cart-summary { margin-top: 20px; padding: 10px; border: 1px solid #ccc; background-color: #f9f9f9; }
</style>
</head>
<body>
<h1>Our Products</h1>
<%
try {
if (p.getId() == productId) {
productToAdd = p;
break;
if (productToAdd != null) {
if (cart == null) {
}
cart.add(productToAdd);
session.setAttribute("shoppingCart", cart);
} else {
} catch (NumberFormatException e) {
%>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
</td>
</tr>
<% } %>
</tbody>
</table>
<div class="cart-summary">
<%
} else {
double total = 0;
out.println("<ul>");
total += item.getPrice();
out.println("</ul>");
%>
<%
if ("true".equals(request.getParameter("clear_cart"))) {
session.removeAttribute("shoppingCart");
%>
</div>
</body>
</html>
```
**Expected Output:**
* You will see a table listing products (Laptop, Mouse, Keyboard, Monitor).
* Clicking "Add to Cart" will add the item to a "Your Shopping Cart" section below the table, and the
total price will update.
---
```java
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
// Getters
// Setters (optional)
```
**`employees.jsp`**
```jsp
<%@ page import="com.example.model.Employee" %> <%-- Adjust package if you changed it --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Employee Records</title>
<style>
table { width: 80%; border-collapse: collapse; margin: 20px 0; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Employee Records</h1>
<%
// Apply filters
filteredEmployees = filteredEmployees.stream()
.collect(Collectors.toList());
filteredEmployees = filteredEmployees.stream()
.collect(Collectors.toList());
%>
<br><br>
<br><br>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
<% } %>
<% } %>
</tbody>
</table>
</body>
</html>
```
**Expected Output:**
* Initially, you will see a table listing all simulated employee records.
* Above the table, there will be a search form for "Search by Name" and "Search by Department".
* Entering text in either field and clicking "Search" will filter the table to show only matching
employees.
* Clicking "Clear Search" will reset the table to show all employees.