Processing forms of a web page

As you know, in any web application, we can send and receive data from the server. In a web application, we send the data by filling out forms, and submitting this form to the server. Spring MVC also provides support for form handling of the client end by displaying the form, validating the form data, and submitting this form data.

Basically, Spring MVC handles the form displaying and form processing first. In the Bank management application, you will need to create a new user, and open a new account in the bank, so, let's create a controller class, AccountController, with a single request-handling method for displaying the account open form, as follows:

    package com.packt.patterninspring.chapter10.bankapp.web.controller; 
 
    import org.springframework.stereotype.Controller; 
    import org.springframework.web.bind.annotation.GetMapping; 
 
    @Controller 
    public class AccountController { 
    
     @GetMapping(value = "/open-account") 
     public String openAccountForm (){ 
         return "accountForm"; 
    } 
   } 

The openAccountForm() method's @GetMapping annotation declares that it will handle the HTTP GET requests for /open-account. It's a simple method, taking no input and only returning a logical view named accountForm. We have configured InternalResourceViewResolver, which means that the JSP at /WEB-INF/views/accountForm.jsp will be called on to render the open account form.

Here's the JSP you'll use for now:

    <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> 
    <html> 
     <head> 
         <title>Bank Management System</title> 
         <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />" > 
     </head> 
     <body> 
         <h1>Open Account Form</h1> 
          <form method="post"> 
           Account Number:<br> 
           <input type="text" name="id"><br> 
           Account Name:<br> 
           <input type="text" name="name"><br> 
           Initial Balance:<br> 
           <input type="text" name="balance"><br> 
           <br> 
           <input type="submit" value="Open Account"> 
           </form>  
    </body> 
  </html>    

As you can see in the preceding code, we have an open account form. It has some fields such as AccountId, Account Name, and Initial Balance. This JSP page has the <form> tag for the form, and this <form> tag doesn't have any action parameter. This means that when we submit this form, it will post the form data to the same URI /open-account with the POST HTTP method call. The following screenshot displays the account form:

Let's add another method to handle the call for the HTTP POST method with the same URI, /open-account.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset