Java Exercise
In this exercise, you will develop a Java web application using servlets and JSP. You will implement a servlet that processes HTTP requests, handles form data, and displays the information in a JSP page. This exercise will help you understand how servlets interact with JSP pages to generate dynamic content in web applications.
Instructions:
- Set up your development environment with a server that supports servlets and JSPs (e.g., Apache Tomcat).
- Create a Java servlet that processes GET and POST requests.
- Develop an HTML form that submits data to the servlet.
- From the servlet, process the form information and pass it to a JSP page.
- In the JSP page, display the received data dynamically.
This exercise will help you understand the basic structure of a Java web application, using servlets for data processing and JSPs for generating dynamic content.
View Example Code
1. HTML Form (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="ProcessServlet" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Send">
</form>
</body>
</html>
2. Servlet for processing data (ProcessServlet.java)
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/ProcessServlet")
public class ProcesarServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
request.setAttribute("name", name);
request.setAttribute("email", email);
request.getRequestDispatcher("response.jsp").forward(request, response);
}
}
3. JSP page to display the response (response.jsp)
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Server Response</title>
</head>
<body>
<h2>Information Received</h2>
<p>Name: ${requestScope.name}</p>
<p>Email: ${requestScope.email}</p>
</body>
</html>
Output:
Information Received
Name: Juan Pérez
Email: [email protected]
This program demonstrates how to use **Servlets** and **JSPs** to handle forms and process data submitted from a web page. **Servlets receive and process information, while JSPs allow you to generate dynamic HTML responses.**