Implementing Form Submission and Page Redirection in Java Web Applications
Handling Form Submission
Web applications frequently require data submission from users. In Java-based web development, HTML forms are the primary mechanism for collecting and sending data to the server for processing.
Here is an example of a basic HTML form designed to capture a user's credentials:
<form action="processCredentials" method="post">
<label for="userInput">Username:</label>
<input type="text" id="userInput" name="userInput"><br><br>
<label for="passInput">Password:</label>
<input type="password" id="passInput" name="passInput"><br><br>
<input type="submit" value="Submit">
</form>
This form uses the POST method to send data to a server endpoint named processCredentials. The subsequent section details the server-side component that handles this request.
Server-Side Processing with Servlets
Servlets are Java classes that manage HTTP requests. They can extract parameters from the incoming request, perform logic, and determine the appropriate response.
The following servlet processes the submitted username and password, then redirects the user based on the validation outcome.
import java.io.IOException;
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("/processCredentials")
public class CredentialProcessor extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String submittedUser = req.getParameter("userInput");
String submittedPass = req.getParameter("passInput");
if ("validUser".equals(submittedUser) && "securePass".equals(submittedPass)) {
resp.sendRedirect("welcome.jsp");
} else {
resp.sendRedirect("error.jsp");
}
}
}
This servlet retireves the userInput and passInput parameters. If they match predefined values, the user is redirected to a welcome page; otherwise, they are sent to an error page using the HttpServletResponse.sendRedirect() method.
Client Redirection
The sendRedirect method instructs the client's browser to request a new URL, rseulting in a page change. The target pages should be simple HTML or JSP files.
Example of a success page (welcome.jsp):
<html>
<head>
<title>Access Granted</title>
</head>
<body>
<h2>Authentication Successful</h2>
<p>Welcome, validUser.</p>
</body>
</html>
Example of an error page (error.jsp):
<html>
<head>
<title>Access Denied</title>
</head>
<body>
<h2>Authentication Failed</h2>
<p>Invalid username or password provided.</p>
</body>
</html>