If you have a web application, then you have a form some where in you application, may be its a sign up form or login form but you have it buddy. Now forms are not bad if you know how to handle them, this is where frameworks like Spring MVC comes to rescue like my favourite Buzz Lightyear.

Form Anatomy

Lets take a look at the anatomy of a web form, it usually starts with a <form> tag.

<form action="/action" method="post">
	<input type="text" name="username">
	<input type="password" name="password">
	<button type="submit" >Submit</button>
</form>

The action specify the url where the data is going to be submitted, this is usually the url for you controller or servlet, method has to be one of the allowed http method, usually for form submission, it is almost always post.

Now once you hit submit, the data gets stored in a string in form of name value pair, like following.

username=buzz+lightyear&password=to+infinity+and+beyond

On the server side you can retrieve the form values using request.getAttribute(“username”) but it would very quickly become messy with lots of form fields.

@ModelAttribute annotation

Spring MVC does a fantastic job of collecting our form values and populating it in any object of our choice and hand it over to our controller method. Lets look at our model object.

 public class User {

    private String username;

    private String password;

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }
}

The most important thing to note here is that the variable name in the receiving object and form element has to match for the automatic population to work. So if our username variable is spelled as userName while in html form we specified as username with small case, spring would not be able to populate it.

 @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String doLogin(@ModelAttribute User user) {
        if (user.getUsername().equals("Buzz Lightyear"))
            return "/infinity.jsp";
        else
            return "coldSpace/.jsp";
    }

As you can see we have implemented a very tight security control to only allow our super hero Buzz Lightyear to have access to infinity, while this kind of strict control may not be necessary for your application. You can implement any kind of logic once you have the form data in an object form.

This seems all fine but what about number or date fields?

Type conversion

Spring would automagically convert your form variable from string to required data type which is mapped to your object. We would be looking at custom bindings and custom converters in details over next few posts, keep reading and enjoy.


Author

Nitiz

There are currently no comments.

Bitnami