Managing Form Data Using MVC Architecture in Advanced Java
Course: Advanced Java Training
Topic: Managing Form Data Using MVC Architecture
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction
Managing form data using MVC (Model-View-Controller) architecture is an important concept in Advanced Java web development. Web applications frequently use forms to collect information such as names, email addresses, login credentials, employee details, student registrations, and customer orders.
When a user submits a form, the application must receive the submitted values, validate them, process the required business operations, and return an appropriate response. MVC organizes these responsibilities into three components: Model, View, and Controller.
In a traditional Java web application, Servlets commonly act as controllers, JSP pages act as views, and JavaBeans or POJOs represent model data. Business services and DAO classes may be used to process form information and interact with a database. This separation makes form handling easier to maintain, test, and extend.
2. Learning Objectives
- Understand the role of MVC architecture in form processing.
- Learn how HTML forms submit data to Java Servlets.
- Read form parameters using HttpServletRequest.
- Create Java model classes to represent form data.
- Validate user input on the server side.
- Pass data between Servlets and JSP pages.
- Display success messages and validation errors.
- Understand request forwarding and redirection.
- Apply security practices while processing form submissions.
3. What Is MVC Architecture?
MVC stands for Model-View-Controller. It is a software design pattern that separates an application into three related components, each with a specific responsibility.
3.1 Model
The Model represents the application's data and may include business logic and data-access components. In Java, it can consist of JavaBeans, POJOs, service classes, and DAO classes.
Responsibilities:
- Represent form data using Java objects.
- Apply or support business validation.
- Perform application-specific processing.
- Coordinate database operations through data-access components.
- Provide processed data to the controller.
For example, a Student model may contain a student's name, email address, and course selection.
3.2 View
The View represents the user interface. It displays forms, labels, input fields, validation messages, and processed results.
Common Java web technologies for views include HTML, CSS, JSP, Expression Language (EL), and JSTL.
Responsibilities:
- Display the form to the user.
- Collect information through input controls.
- Display validation errors and confirmation messages.
- Show submitted or processed data.
- Keep database operations and complex business logic out of the presentation.
3.3 Controller
The Controller receives HTTP requests and coordinates the application's response. In a Servlet/JSP MVC application, a Java Servlet commonly acts as the controller.
Responsibilities:
- Receive GET and POST requests.
- Read submitted values using request parameters.
- Perform request-level validation and type conversion.
- Call model or service components.
- Store data and error messages in request attributes.
- Forward to the appropriate JSP or redirect the browser.
4. MVC Architecture Flow for Form Processing
User / Browser
|
| 1. Open registration form
v
RegistrationServlet
|
| 2. Forward to form view
v
registration.jsp
|
| 3. User submits form using POST
v
RegistrationServlet
|
| 4. Read and validate submitted data
v
Student Model / RegistrationService
|
| 5. Process data or save through DAO
v
Database (if required)
|
| 6. Return processing result
v
RegistrationServlet
|
| 7. Forward to result view
v
success.jsp or registration.jsp
|
v
User / Browser
The controller coordinates the complete request flow. The view is responsible for presenting information, while the model and supporting service or DAO components handle data representation, business processing, and persistence.
5. Understanding HTML Forms
An HTML form collects information from a user and submits it to a server endpoint. The form's action attribute specifies where the data is sent, while the method attribute specifies how the request is submitted.
<form action="register" method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Register</button>
</form>
Important attributes:
action: Defines the endpoint that receives the form submission.
method: Defines the HTTP method, commonly GET or POST.
name: Identifies a form field when the browser submits its value.
id: Identifies an element in the HTML document and can associate a label with it.
required: Requests browser-side validation that a field is completed.
type: Specifies the expected kind of input, such as text, email, password, or number.
For a field to be submitted as a normal form parameter, it generally needs a name attribute. Client-side validation improves usability, but it does not replace server-side validation.
6. GET and POST Methods
| Feature |
GET |
POST |
| Common purpose |
Retrieve or display information |
Submit data for processing or modification |
| Data location |
Usually included in the URL query string |
Usually included in the request body for standard form submissions |
| Visibility |
Parameters can appear in the URL and browser history |
Form values are not normally placed in the URL |
| Typical use |
Open a registration page or search records |
Register a user or update a record |
| Security consideration |
Do not put secrets in query parameters |
HTTPS and appropriate application security are still required |
POST does not automatically encrypt form data. Use HTTPS to protect information in transit, and use suitable authentication, authorization, and validation for sensitive operations.
7. Reading Form Data in a Servlet
The HttpServletRequest object provides methods for accessing submitted form values.
7.1 Using getParameter()
The getParameter() method retrieves one value for a named request parameter. It returns a String or null if the parameter is absent.
String name = request.getParameter("name");
String email = request.getParameter("email");
For example, if the form submits the name value as "Aarav", the variable name receives that text.
7.2 Handling Missing Values
Always consider the possibility that a field is missing, empty, or malformed. A browser can be bypassed, and requests can be constructed manually.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
// Handle the missing or blank name.
}
7.3 Reading Multiple Values
Some form controls, such as checkboxes with the same name, can submit multiple values. Use getParameterValues() to retrieve them.
String[] skills = request.getParameterValues("skills");
Check whether the returned array is null before processing it.
8. Creating a Model Class Using JavaBean Principles
A model class stores form values in a structured Java object. A simple JavaBean commonly has private properties, a public no-argument constructor, and public getter and setter methods.
Create a class named Student.java inside the model package.
package com.example.model;
public class Student {
private String name;
private String email;
private String course;
public Student() {
}
public Student(String name, String email, String course) {
this.name = name;
this.email = email;
this.course = course;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Explanation:
- The private fields store student information.
- The constructor initializes the object.
- Getter methods retrieve property values.
- Setter methods update property values.
- The model can be passed between the controller, service, and view.
9. Building an MVC Registration Form
In this example, a student submits a registration form. A Servlet receives the form values, performs basic validation, creates a Student object, and forwards the result to a JSP view.
9.1 Suggested Project Structure
StudentRegistration/
├── src/main/java/
│ └── com/example/
│ ├── model/
│ │ └── Student.java
│ └── controller/
│ └── RegistrationServlet.java
└── src/main/webapp/
└── WEB-INF/
└── views/
├── registration.jsp
└── success.jsp
This is a basic MVC example without database persistence. A larger application can add service and DAO classes to handle business rules and database operations. The JSP files are stored under WEB-INF so users access them through the controller rather than requesting them directly.
9.2 Create the Registration Form View
Create registration.jsp to display the form.
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
</head>
<body>
<h1>Student Registration</h1>
<form action="${pageContext.request.contextPath}/register"
method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="course">Course:</label>
<select id="course" name="course" required>
<option value="">Select a course</option>
<option value="Java">Java</option>
<option value="Python">Python</option>
<option value="Web Development">Web Development</option>
</select>
<br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
The form sends the values to the /register endpoint using POST. The context path expression helps the form work when the application is deployed under a context path other than the server root.
9.3 Create the Controller Servlet
Create RegistrationServlet.java. It receives the request, reads the submitted values, validates them, and forwards the result to the appropriate JSP page.
package com.example.controller;
import com.example.model.Student;
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("/register")
public class RegistrationServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher(
"/WEB-INF/views/registration.jsp"
).forward(request, response);
}
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
String errorMessage = null;
if (name == null || name.trim().isEmpty()) {
errorMessage = "Full name is required.";
} else if (email == null ||
!email.trim().matches(
"^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")) {
errorMessage = "Enter a valid email address.";
} else if (!isAllowedCourse(course)) {
errorMessage = "Please select a valid course.";
}
if (errorMessage != null) {
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher(
"/WEB-INF/views/registration.jsp"
).forward(request, response);
return;
}
Student student = new Student(
name.trim(),
email.trim(),
course
);
request.setAttribute("student", student);
request.getRequestDispatcher(
"/WEB-INF/views/success.jsp"
).forward(request, response);
}
private boolean isAllowedCourse(String course) {
return "Java".equals(course)
|| "Python".equals(course)
|| "Web Development".equals(course);
}
}
How this controller works:
- The
doGet() method displays the registration form.
- The
doPost() method processes the submitted form.
- The Servlet reads parameters from the request.
- It checks whether required fields are present and valid for this example.
- If validation fails, it adds an error message and forwards back to the form.
- If validation succeeds, it creates a Student object and stores it as a request attribute.
- The request is forwarded to the success view.
Important: This example uses Jakarta Servlet imports. Older Java EE projects may use javax.servlet instead of jakarta.servlet. Use the API version supported by your application server. The email check is a basic example, not complete email-address verification.
9.4 Display Validation Errors in the JSP
Update registration.jsp to show a message when the controller detects invalid input.
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
</head>
<body>
<h1>Student Registration</h1>
<p style="color: red;">
${requestScope.errorMessage}
</p>
<form action="${pageContext.request.contextPath}/register"
method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="course">Course:</label>
<select id="course" name="course" required>
<option value="">Select a course</option>
<option value="Java">Java</option>
<option value="Python">Python</option>
<option value="Web Development">Web Development</option>
</select>
<br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
In a production JSP, use JSTL conditional tags to avoid displaying an empty error paragraph, and preserve previously submitted non-sensitive values where appropriate. Always escape user-controlled values when rendering them in HTML.
9.5 Create the Success View
Create success.jsp to display the data supplied by the controller.
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration Successful</title>
</head>
<body>
<h1>Registration Successful</h1>
<p>Your registration details were received.</p>
<p>Name: ${requestScope.student.name}</p>
<p>Email: ${requestScope.student.email}</p>
<p>Course: ${requestScope.student.course}</p>
<a href="${pageContext.request.contextPath}/register">
Register Another Student
</a>
</body>
</html>
Expression Language accesses the properties of the Student object. For example, ${requestScope.student.name} uses the Student object's name property. Ensure the application uses an appropriate JSP/EL version and applies HTML escaping when displaying untrusted values.
10. How Data Moves Between MVC Components
Java web applications commonly use request parameters, Java objects, and request attributes to move form data through MVC.
| Method or Component |
Purpose |
Example |
request.getParameter() |
Reads a submitted form value |
request.getParameter("email") |
| Model object |
Groups related values into an object |
new Student(name, email, course) |
request.setAttribute() |
Stores data for the current request |
request.setAttribute("student", student) |
RequestDispatcher.forward() |
Passes the same request to a server-side resource |
Forward to a JSP view |
| JSP Expression Language |
Reads data in the view |
${requestScope.student.name} |
response.sendRedirect() |
Instructs the browser to make another request |
Redirect to a result endpoint |
11. Forwarding vs. Redirecting
Forwarding and redirecting are two different ways to control the response after processing form data.
11.1 RequestDispatcher.forward()
Forwarding transfers control to another server-side resource while keeping the same request and response objects.
request.setAttribute("message", "Form processed successfully");
request.getRequestDispatcher(
"/WEB-INF/views/success.jsp"
).forward(request, response);
The request attributes remain available to the forwarded JSP. The browser's address bar generally continues to show the original URL.
11.2 response.sendRedirect()
Redirecting sends a redirect response to the browser. The browser then makes a new request to the specified URL.
response.sendRedirect(
request.getContextPath() + "/registration-success"
);
Because the browser makes a new request, request attributes from the original request are not automatically carried over.
11.3 Comparison Table
| Feature |
Forward |
Redirect |
| Where it occurs |
Inside the server |
Through the browser |
| Request |
Uses the existing request |
Creates a new request |
| Request attributes |
Remain available |
Not automatically preserved |
| Browser URL |
Usually remains unchanged |
Changes to the redirected URL |
| Typical use |
Display a form with validation errors |
Redirect after a successful POST |
12. The Post/Redirect/Get Pattern
The Post/Redirect/Get (PRG) pattern helps prevent accidental resubmission when users refresh a page after submitting a form. After successfully processing a POST request, the controller redirects the browser to a GET endpoint.
// After successfully processing the submitted form:
response.sendRedirect(
request.getContextPath() + "/registration-success"
);
The /registration-success endpoint should handle GET and display the result. If a confirmation message must survive the redirect, use an appropriate mechanism such as a short-lived session message or a server-side record identified by a safe token. Do not rely on request attributes surviving a redirect.
13. Server-Side Validation of Form Data
Validation checks whether submitted values meet the application's requirements. Browser validation is useful for user experience, but server-side validation is essential because clients can bypass browser controls.
13.1 Required Field Validation
if (name == null || name.trim().isEmpty()) {
errorMessage = "Name is required.";
}
13.2 Numeric Validation
String ageValue = request.getParameter("age");
try {
int age = Integer.parseInt(ageValue);
if (age < 18 || age > 120) {
// Reject the value if it falls outside
// the application's permitted range.
}
} catch (NumberFormatException ex) {
// Handle missing or invalid numeric input.
}
Check for null or blank values before converting strings into numbers.
13.3 Email Validation
A basic pattern can catch common mistakes, but regular expressions do not establish that an address exists or belongs to the user. Applications that require verified email addresses should use a suitable validation and verification process.
13.4 Business Validation
Some rules are more than simple format checks. For example, a course registration system might reject a registration if the course is closed. Such rules should be enforced in the business service, even if the controller also performs basic request validation.
14. Managing Validation Errors
When form validation fails, the controller should provide a useful message and return the user to the form. Avoid exposing database exceptions, stack traces, or other internal details.
A more structured approach can use a collection of errors:
Map<String, String> errors = new HashMap<>();
if (name == null || name.trim().isEmpty()) {
errors.put("name", "Name is required.");
}
if (email == null || email.trim().isEmpty()) {
errors.put("email", "Email is required.");
}
if (!errors.isEmpty()) {
request.setAttribute("errors", errors);
request.getRequestDispatcher(
"/WEB-INF/views/registration.jsp"
).forward(request, response);
return;
}
The JSP can then display each field's corresponding message. For production code, import the appropriate collection classes, use a consistent validation strategy, and escape messages and user-controlled content correctly.
15. Handling Form Data with a Database
In a complete application, a valid form submission may need to be saved in a database. The controller should call a service or model operation rather than execute SQL directly.
Controller Servlet
|
v
RegistrationService
|
v
StudentDAO
|
v
Database
The service applies business rules and coordinates the operation. The DAO performs database access using JDBC or another persistence technology. SQL statements should use prepared parameters, and database resources must be managed reliably.
For example, a DAO may execute an insert statement using PreparedStatement. The application should also handle duplicate records, database errors, transaction requirements, and any required authorization checks.
16. Common Mistakes in MVC Form Handling
- Putting all code in JSP: Mixing HTML, business logic, and database operations makes the application difficult to maintain.
- Putting all logic in the Servlet: Large controllers become difficult to test and reuse. Delegate business operations to services.
- Ignoring missing parameters: A request may omit a field or submit an empty value.
- Trusting browser validation: Always validate input on the server.
- Using GET for sensitive form submissions: Sensitive values should not be placed in URL query parameters.
- Confusing forward and redirect: Request attributes do not automatically survive a redirect.
- Displaying unescaped user input: Untrusted data rendered in HTML can create cross-site scripting risks.
- Hardcoding sensitive configuration: Keep credentials and secrets out of source code.
- Ignoring CSRF protection: State-changing forms should use appropriate cross-site request forgery protections when required.
- Accepting arbitrary option values: Validate submitted select and checkbox values against allowed choices on the server.
17. Security Best Practices
- Use HTTPS to protect form submissions in transit.
- Validate all incoming data on the server side.
- Apply authentication and authorization checks to protected operations.
- Use CSRF tokens or the relevant framework's CSRF protection for state-changing requests.
- Use prepared statements for SQL operations.
- Escape user-controlled content when displaying it in HTML.
- Do not store passwords in plain text; use an established password-hashing algorithm and library.
- Do not log passwords, session tokens, or other sensitive form values.
- Use allowlists for fixed choices such as course names or account roles.
- Return generic error messages to users and log technical details securely.
18. Testing MVC Form Processing
Testing helps ensure that form data is handled correctly in both normal and exceptional situations.
| Test Case |
Input |
Expected Result |
| Valid submission |
Valid name, email, and course |
Student object is created and the success view is shown. |
| Missing name |
Blank name |
Validation error is shown. |
| Missing email |
Empty email value |
Validation error is shown. |
| Invalid course |
Course value not in the allowed list |
Submission is rejected. |
| Unexpected request |
Missing or malformed parameters |
Application handles the request safely. |
| Refresh after successful submission |
Refresh the result page |
PRG can prevent repeating the original POST. |
Controller tests can verify request handling and navigation. Service tests can verify business rules, while DAO integration tests can verify database behavior. Each test type should focus on the responsibilities of the component being tested.
19. Practical Exercises
- Create a student registration form using HTML and JSP.
- Create a Student JavaBean with name, email, and course properties.
- Create a Servlet that handles GET requests to display the form.
- Handle POST requests and retrieve values using
getParameter().
- Validate all required fields on the server.
- Display field-specific error messages when input is invalid.
- Display the submitted student details on a separate JSP page.
- Extend the application with a service class and a DAO.
- Save valid student registrations in a database using prepared statements.
- Implement a redirect after successful registration and test the PRG pattern.
20. Interview Questions and Answers
Q1. What is MVC architecture?
Answer: MVC is a design pattern that separates an application into Model, View, and Controller. The Model represents data and application behavior, the View presents information, and the Controller handles requests and coordinates processing.
Q2. How is form data handled in a Java Servlet?
Answer: A Servlet reads submitted values through methods such as request.getParameter() and request.getParameterValues(). It validates the input, invokes the appropriate application logic, and prepares a response.
Q3. What is the role of JSP in MVC?
Answer: JSP acts as the View. It renders HTML and displays data supplied by the controller, commonly using Expression Language and JSTL.
Q4. What is the difference between getParameter() and getParameterValues()?
Answer: getParameter() returns one parameter value as a String. getParameterValues() returns an array of values, which is useful for multiple selections such as checkboxes.
Q5. Why should server-side validation be performed?
Answer: Client-side validation can be bypassed. Server-side validation ensures that submitted data is checked before business operations or database changes occur.
Q6. What is the difference between forward and redirect?
Answer: Forwarding transfers processing to another server-side resource using the existing request. Redirecting tells the browser to make a new request to another URL.
Q7. What is a JavaBean in form handling?
Answer: A JavaBean is a Java class that commonly uses private properties, a public no-argument constructor, and getter and setter methods. It can represent form data as a structured object.
Q8. What is the Post/Redirect/Get pattern?
Answer: PRG redirects the browser after a successful POST so that refreshing the resulting page performs a GET instead of resubmitting the original form.
Q9. Why should SQL code be kept out of a Servlet?
Answer: Keeping SQL in a DAO or repository separates persistence from request handling, improves testing, and makes the application easier to maintain.
Q10. How can form processing be made more secure?
Answer: Use HTTPS, server-side validation, authorization checks, CSRF protection where appropriate, prepared statements, safe output escaping, and secure handling of sensitive information.
21. Quick Revision Checklist
- MVC means Model-View-Controller.
- HTML forms collect user input and submit it to a controller endpoint.
- Servlets commonly serve as controllers in Java web applications.
- JSP pages commonly serve as views.
- JavaBeans and POJOs can represent form data.
getParameter() reads a single parameter value.
getParameterValues() reads multiple values for a parameter.
setAttribute() stores data for a request or another supported scope.
RequestDispatcher.forward() forwards the existing request on the server.
sendRedirect() instructs the browser to make a new request.
- Server-side validation is required even when HTML validation is used.
- Service and DAO classes help keep business rules and database operations separate.
- Use secure output handling and suitable protection for state-changing forms.
22. Conclusion
Managing form data using MVC architecture provides a structured way to build Java web applications. The View collects and displays information, the Controller receives and coordinates requests, and the Model represents data and application behavior.
Using Servlets, JSP, JavaBeans, and suitable service or DAO classes helps keep responsibilities separate. Proper server-side validation, safe error handling, secure database access, and clear navigation between views make form-processing applications more reliable and maintainable.
Learn more through the Advanced Java Training Course, register for a course demo, or visit the JustAcademy website.