[Spring Practice – Building Spring Web Applications] 1.10 Processing forms

Introduction

Web application function

○ Provide content
○ User fills in the form
○ Submit data

Spring MVC controller provided

○ Process form display
○ Support for user submitted data

  1. In the Spittr app, a registration form is required for new users.
  2. SpitterController is a new controller that currently only has one request handling method for displaying the registration form.
    Program Listing 5.13 SpitterController: Displays a form to allow users to register for the application file

According to the configured InternalResourceViewResolver, the JSP “/WEB-INF/views/registerForm.jsp” will be used to render the registration form.

  1. Although the showRegistrationForm() method is simple, it still needs to be tested.
  2. Because of the simplicity of the method, testing is relatively simple. Program Listing 5.14 Test the controller method of displaying the form file Note
  3. The name of the view is registerForm, so the name of the JSP should be registerForm.jsp.
  4. registerForm.jsp must contain an HTML tag for the user to enter information to register the application

Program Listing 5.15 JSP that renders the registration form file

In the JSP, there is a basic HTML form that contains form fields for recording the user’s first name, last name, username, and password, as well as a submit button. In this JSP,

The tag does not have an action attribute set. In this case, when the form is submitted, it will be submitted to the same URL path as when it was displayed, which is “/spitter/register”. This means that this HTTP POST request needs to be handled on the server side.
file Now, we need to add a method in Spitter-Controller to handle this Submission of the form.

Figure 5.5 The registration page provides a form, which will be processed by SpitterController to complete the function of adding new users to the application.

5.4.1 Writing a controller to process the form

When handling the POST request for the registration form, the controller needs to receive the form data and save it as a Spitter object.
To prevent duplicate submissions, the browser should be redirected to the newly created user’s basic information page.
These behaviors can be tested via the shouldProcessRegistration() method.
Program Listing 5.16 Test the controller method for processing the form file

  1. When handling POST requests, it is best to redirect after the request is processed to prevent browser refreshes from causing repeated form submissions.
  2. In this test, it is expected that the request will be redirected to “/spitter/jbauer”, which is the basic information page of the newly created user.
  3. Finally, the test will verify whether the mock implementation of SpitterRepository actually saves the data submitted by the form.
  4. Now, we need to implement the controller method that handles form submission.
  5. Through the shouldProcessRegistration() method, we can see that the new SpitterController does not do much. Listing 5.17 Processes the submitted form and registers the new user

file

 Based on the previously created showRegistrationForm() method, we have added a new processRegistration() method. This method accepts a Spitter object as a parameter, which has firstName, lastName, username and password properties. These properties will be populated with parameters of the same name from the request.
    When the InternalResourceViewResolver sees the "redirect:" prefix in the view format, it knows to resolve it as a redirect rule, not the name of the view. In this case, it redirects the view to the user's basic information page. For example, if the value of the Spitter.username property is "jbauer", then the view will be redirected to "/spitter/jbauer".

According to the tests in Listing 5.16, our task should be completed. However, in SpitterController, we also need to add a handler method to handle the request for the basic information page. The showSpitterProfile() method will accomplish this task. 

file SpitterRepository obtains a Spitter object through the user name, and the showSpitterProfile() method will obtain The object is added to the model, and the logical view name “profile” of the basic information page is returned. Like the other views shown in this chapter, the Basic Information view is very simple.

Figure 5.6 shows the basic information page rendered in a web browser. The following is the output after sorting and polishing this content: What happens if username or password is not sent in the form? Or, what will be the impact if the value of firstName or lastName is empty or too long? Next, let’s look at how to add validation to form submissions to avoid data inconsistencies.

Figure 5.6 The basic information page of Spittr shows the user’s situation. This information is filled into the model by SpitterController.

5.4.2 Verification Form

If the username or password text field is empty when the user submits the form, the username or password attribute in the newly created Spitter object will be an empty string. This behavior can cause security issues because anyone can log into the application simply by submitting an empty form.
To maintain a certain level of anonymity, we should prevent users from submitting empty firstName and/or lastName. A good approach is to limit the length of these input fields to ensure that their values are within a reasonable range and avoid misuse.
To handle validation, you can add code in the processRegistration() method to check the validity of the value. If the value is illegal, you can redisplay the registration form to the user. While this approach is short and simple, adding a few extra if statements isn’t a big deal.
Rather than letting validation logic obfuscate processor methods, take advantage of Spring’s support for the Java Validation API (JSR-303). Starting with Spring 3.0, support for the Java validation API is provided in Spring MVC.
Using the Java validation API does not require additional configuration, just make sure the implementation of the API, such as Hibernate Validator, is included in the classpath.
The Java Validation API defines multiple annotations that can be placed on properties to limit the values of these properties. All annotations are located in the javax.validation.constraints package. Table 5.1 lists these verification annotations.
Table 5.1 Verification annotations provided by Java verification API

Note Description

file

In addition to the annotations in Table 5.1, the Java verification API implementation may provide additional verification annotations. At the same time, you can also define your own restrictions. But for our purposes, we will focus on the two core constraints in the table above.
Please consider the constraints you want to add to the Spitter domain, which seems to require the use of @NotNull and @Size annotations. All we have to do is add these annotations to the Spitter’s properties. The following program listing shows the Spitter class with validation annotations added to its properties.
Listing 5.18 Spitter: Contains the domain to be submitted to the Spittle POST request file @NotNull annotation ensures that the value is not null. @Size annotation limits their length to between the maximum and minimum values. For Spittr applications, this means that the user must complete a registration form and the length of the value must be within a given range.

We have added verification annotations to Spitter, and next we need to modify the processRegistration() method to apply the verification function. Shown below is the processRegistration() method with validation enabled. Program Listing 5.19 processRegistration(): Ensure that the submitted data is legal file This has changed significantly from the original processRegistration() method in Listing 5.17. The @Valid annotation is added to the Spitter parameter to inform Spring that the object needs to be verified. Adding validation restrictions still does not prevent form submission Adding validation restrictions on the Spitter property does not prevent form submission. Even if the user does not fill in a field or the value of a field exceeds the maximum length, the processRegistration() method will still be called.

Handling verification errors

Therefore, we need to handle validation errors as shown in the processRegistration() method.
If validation errors occur, these errors can be accessed through the Errors object, which is now passed as a parameter to the processRegistration() method.
It should be noted that the Errors parameter follows the parameter with the @Valid annotation, and the @Valid annotation annotates the parameters to be verified.

processRegistration() method

The first thing the processRegistration() method does is call Errors.hasErrors() to check if there are any errors.

What happens if there is an error?

If there are errors, Errors.hasErrors() will return to registerForm, the view of the registration form.
This allows the user’s browser to return to the registration form page so they can correct errors and retry submission.
For now, an empty form will be displayed, but in the next chapter we will display the originally submitted values in the form and report validation errors back to the user.

What would happen if there were no errors

If there are no errors, the Spitter object will be saved through the Repository, and the controller will redirect to the basic information page as before.

This article is published by OpenWrite, a blog posting platform!