Java Servlets Tutorial Part 2: Handling Forms & Databases
Document Details

Uploaded by EffortlessOnyx288
Tags
Summary
This Java Servlets tutorial extends knowledge of Java Servlets by learning how to handle user input through HTML forms and interact with a database. The tutorial covers handling POST requests, connecting to a MySQL database using JDBC and performing basic database operations. It uses NetBeans with GlassFish.
Full Transcript
Java Servlets Tutorial - Part 2: Handling Forms and Database Integration Using NetBeans and GlassFish Objective: In this tutorial, you'll extend your knowledge of Java Servlets by learning how to handle user input through HTML forms and interact with a database. By the end, you'll be able to:...
Java Servlets Tutorial - Part 2: Handling Forms and Database Integration Using NetBeans and GlassFish Objective: In this tutorial, you'll extend your knowledge of Java Servlets by learning how to handle user input through HTML forms and interact with a database. By the end, you'll be able to: Handle POST requests from forms. Connect to a MySQL database using JDBC. Perform basic database operations (CRUD: Create, Read, Update, Delete). Prerequisites Completion of Java Servlets Tutorial Part 1 (basic servlet setup in NetBeans with GlassFish). MySQL Database installed (or any other relational database). JDBC Driver for MySQL (e.g., mysql-connector-java). Step-by-Step Tutorial 1. Setting Up a Database Step 1: Install and Configure MySQL If MySQL is not installed on your machine, download it from here. Once installed: 1. Create a database for this tutorial. You can do this via MySQL Workbench or the Command Line. CREATE DATABASE userdb; USE userdb; Step 2: Create a Table for Storing User Data CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL UNIQUE ); 2. Creating a Dynamic Web Application in NetBeans If you haven’t already, create a new web project in NetBeans (following the steps from the previous tutorial). Handling Forms in Servlets You will now build a simple form where users can enter their names and email addresses. The servlet will process the form data and store it in the database. Step 1: Create an HTML Form In the Web Pages directory, create a new HTML file called register.html. User Registration User Registration Form Name: Email: The form submits data to the /register URL using the POST method. Connecting to a Database Using JDBC Step 2: Set Up JDBC in NetBeans 1. Download the MySQL Connector/J 2. In NetBeans, right-click on the Libraries node in your project. 3. Select Add Library > Add JAR/Folder, and add the mysql-connector-java-X.X.X-bin.jar file. Step 3: Create a Servlet to Handle the Form Submission In the Source Packages, create a new servlet named RegisterServlet. package com.example.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; // JDBC URL, username, and password of MySQL server private static final String JDBC_URL = "jdbc:mysql://localhost:3306/userdb"; private static final String JDBC_USER = "root"; private static final String JDBC_PASSWORD = "password"; // Change this to your MySQL password // SQL Insert query private static final String INSERT_QUERY = "INSERT INTO users (name, email) VALUES (?, ?)"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve form parameters String name = request.getParameter("name"); String email = request.getParameter("email"); try { // Load JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish a connection Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); // Prepare the SQL statement PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY); pstmt.setString(1, name); pstmt.setString(2, email); // Execute the update int rowsAffected = pstmt.executeUpdate(); // Close the resources pstmt.close(); conn.close(); // Send a response back to the client if (rowsAffected > 0) { response.getWriter().println("Registration successful!"); } else { response.getWriter().println("Error occurred. Please try again."); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); response.getWriter().println("Database error: " + e.getMessage() + ""); } } } Explanation JDBC URL, Username, Password: The connection details for your MySQL server. DriverManager: Establishes a connection with the database. PreparedStatement: Used to insert form data into the users table. doPost(): Handles the form submission (POST request) and inserts the data into the database. Step 4: Mapping the Servlet In your web.xml, map the RegisterServlet to the /register URL. RegisterServlet com.example.servlet.RegisterServlet RegisterServlet /register Step 5: Running the Application 1. Right-click on your project in NetBeans and choose Run. 2. The application will open in the browser. 3. Navigate to http://localhost:8080/MyFirstServletApp/register.html. 4. Fill in the form and submit. 5. You should see a success message, and the data should be inserted into your MySQL database. Displaying Data from the Database Step 6: Create a Servlet to Display Registered Users Now, let’s create another servlet to display the list of registered users. 1. Create a new servlet named UserListServlet. package com.example.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserListServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String JDBC_URL = "jdbc:mysql://localhost:3306/userdb"; private static final String JDBC_USER = "root"; private static final String JDBC_PASSWORD = "password"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Load JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish a connection Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); // Create a statement Statement stmt = conn.createStatement(); // Execute the query to get all users ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // Display the result in HTML format response.setContentType("text/html"); response.getWriter().println("Registered Users:"); response.getWriter().println(""); while (rs.next()) { response.getWriter().println("" + rs.getString("name") + " (" + rs.getString("email") + ")"); } response.getWriter().println(""); // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); response.getWriter().println("Database error: " + e.getMessage() + ""); } } } Step 7: Mapping the Servlet Update web.xml: UserListServlet com.example.servlet.UserListServlet UserListServlet /users Step 8: Running the Application 1. Restart the GlassFish server. 2. Go to http://localhost:8080/MyFirstServletApp/users. 3. You should see a list of users who registered using the form. Conclusion In this second part of the tutorial, you learned how to handle form data in servlets and integrate it with a MySQL database using JDBC. You now have a working example of how to collect user data through an HTML form, store it in a database, and display it dynamically on a web page. Feel free to expand this project by adding features like form validation, updating and deleting users, and using advanced JDBC features like transactions.