From the course: Complete Guide to Spring MVC

Form data

- [Instructor] Form data. In Spring MVC, form data is typically submitted via HTTP POST requests with a content type of application/x-www-form-urlencoded, which means that the form data is encoded as key-value pairs within the request body. So if you're ever wondering, also, when would you use like multipart/form-data versus the form-urlencoded, here's a great helpful table that you can look at to go through the use cases. So one would be best for simple small alphanumeric key value pairs like form inputs. However, the form data for multipart would be used for transmitting larger or more complex data like files or binary. If file uploads are ever required, then you would need to use the multipart/form-data option. The FormContentFilter is a tool provided within Spring MVC to handle form data submitted via HTTP PUT, PATCH, or DELETE request. It intercepts these requests and then extracts the form data from a request body and makes it accessible through the standard ServletRequest.getParameter methods. And so when you're using the FormContentFilter, there's a few things that you're going to want to do. You're going to want to, one, add a dependency. So ensure you have the Spring Web dependency in your project, which if you're following along this course, you did add that in the beginning when we were in the Spring Initializr. And then you're going to want to update your view. So modify the greeting.html template to display the form and the submitted data. The file I have here is called signup.html, but you can either update your greeting file or create a new file depending on your use case. For this use case that I used in my own example, a form would gather someone's first, last name, and some other information. So I created a separate signup.html file to be able to do that process. Next you're going to want to register filter. So in your Spring configuration, register the form content filter using the bean provided here. And then you're going to want to configure handler mappings. If you're using simple URL handler mapping, ensure it's configured after the form content filter in your Spring configuration to allow the filter to process the request before the handler mapping. And for accessing form data in controllers, in your controller method, you can use the RequestParam annotation to access the data. Again, here for my own example, I've called mine WelcomeController, but yours is your greeting controller class. The FormContentFilter here allows you to handle form data, as I mentioned, submitted by either HTTP PUT, PATCH, or DELETE requests. And then we've registered the filter in our Spring configuration. We're using the standard ServletRequest.getParameter methods to assess form data in our controller. And by using the FormContentFilter, you can provide a more consistent user experience by allowing users to submit form data using different HTTP methods.

Contents