Giter VIP home page Giter VIP logo

gs-handling-form-submission's Introduction

This guide walks you through the process of using Spring to create and submit a web form.

What You Will build

In this guide, you will build a web form, which will be accessible at the following URL: http://localhost:8080/greeting

Viewing this page in a browser will display the form. You can submit a greeting by populating the id and content form fields. A results page will be displayed when the form is submitted.

Starting with Spring Initializr

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs the Spring Web and Thymeleaf dependencies.

The following listing shows the pom.xml file that is created when you choose Maven:

link:initial/pom.xml[role=include]

The following listing shows the build.gradle file that is created when you choose Gradle:

link:initial/build.gradle[role=include]

Create a Web Controller

In Spring’s approach to building web sites, HTTP requests are handled by a controller. These components are easily identified by the @Controller annotation. The GreetingController in the following listing (from src/main/java/com/example/handlingformsubmission/GreetingController.java) handles GET requests for /greeting by returning the name of a View (in this case, greeting). The following View is responsible for rendering the HTML content:

link:complete/src/main/java/com/example/handlingformsubmission/GreetingController.java[role=include]

This controller is concise and simple, but a lot is going on. The rest of this section analyzes it step by step.

The mapping annotations let you map HTTP requests to specific controller methods. The two methods in this controller are both mapped to /greeting. You can use @RequestMapping (which, by default, maps all HTTP operations, such as GET, POST, and so forth). However, in this case, the greetingForm() method is specifically mapped to GET by using @GetMapping, while greetingSubmit() is mapped to POST with @PostMapping. This mapping lets the controller differentiate the requests to the /greeting endpoint.

The greetingForm() method uses a Model object to expose a new Greeting to the view template. The Greeting object in the following code (from src/main/java/com/example/handlingformsubmission/Greeting.java) contains fields such as id and content that correspond to the form fields in the greeting view and are used to capture the information from the form:

link:complete/src/main/java/com/example/handlingformsubmission/Greeting.java[role=include]

The implementation of the method body relies on a view technology to perform server-side rendering of the HTML by converting the view name (greeting) into a template to render. In this case, we use Thymeleaf, which parses the greeting.html template and evaluates the various template expressions to render the form. The following listing (from src/main/resources/templates/greeting.html) shows the greeting template:

link:complete/src/main/resources/templates/greeting.html[role=include]

The th:action="@{/greeting}" expression directs the form to POST to the /greeting endpoint, while the th:object="${greeting}" expression declares the model object to use for collecting the form data. The two form fields, expressed with th:field="{id}" and th:field="{content}", correspond to the fields in the Greeting object.

That covers the controller, model, and view for presenting the form. Now we can review the process of submitting the form. As noted earlier, the form submits to the /greeting endpoint by using a POST call. The greetingSubmit() method receives the Greeting object that was populated by the form. The Greeting is a @ModelAttribute, so it is bound to the incoming form content. Also, the submitted data can be rendered in the result view by referring to it by name (by default, the name of the method parameter, so greeting in this case). The id is rendered in the <p th:text="'id: ' + ${greeting.id}" /> expression. Likewise, the content is rendered in the <p th:text="'content: ' + ${greeting.content}" /> expression. The following listing (from src/main/resources/templates/result.html) shows the result template:

link:complete/src/main/resources/templates/result.html[role=include]

For clarity, this example uses two separate view templates for rendering the form and displaying the submitted data. However, you can use a single view for both purposes.

Make the Application Executable

Although you can package this service as a traditional WAR file for deployment to an external application server, the simpler approach is to create a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance. The following listing (from src/main/java/com/example/handlingformsubmission/HandlingFormSubmissionApplication.java) shows the application class:

link:complete/src/main/java/com/example/handlingformsubmission/HandlingFormSubmissionApplication.java[role=include]

Logging output is displayed. The service should be up and running within a few seconds.

Test the service

Now that the web site is running, visit http://localhost:8080/greeting, where you see the following form:

Form

Submit an ID and message to see the results:

Result

Summary

Congratulations! You have just used Spring to create and submit a form.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.