Form Data Handling

Now we are good at basics of Spring MVC. We will see some frequently used operations with form handling.

What we need to know if we want to create any project is as below. In spring there are many concepts and very difficult to remember. To pass interview below working knowledge with concepts is enough.

  1. Add Form data

  2. Update Form data

  3. Searching option for form

  4. Delete form data

  5. Show Data from controller

We will see all these operations in below example.

welcome-page.jsp


User.java


WelcomeController.java


userController.java



We can pass and use the HttpServletRequest object in a controller method to get access to all request parameters (i.e. GET request).



We can also read form data using @RequestParam annotation. This is a different way for reading form data in the request parameters.

Here, we bind a variable with a value fetched from@RequestParam annotation.

result.jsp



There are set of object made available in JSP pages such as request, response, param, paramValues, cookie, etc.

The param object maps a request parameter name to a single value, while the paramValues maps a request parameter name to an array of values.



When the form is submitted (let’s say for adding a new user), we can bind the user object with form data submitted. How? The model attribute that come with @ModelAttribute annotation is bind-ed to the data submitted.

So, we can bind the user object with the model attribute (call it user for example), and access all the data submitted using the user object

The @ModelAttribute annotation makes the model attribute user available to view pages to access and display it.

This is the method we will be using in our example.



If the data is passed in the request body (i.e. POST request), then, we can access the data using@RequestBody instead.


userForm.jsp


You can use spring tags as well here like below.


employeesList.jsp


Searchuserpage.jsp


userpage.jsp


spring-mvc-demo-servlet.xml keep as it is as previous program.

web.xml keep as it is as previous program.

pom.xml will be as below.


See complete project structure it will look like this.

spring mvc form data handling project structure