Create Login page using Spring MVC

In this article we will learn how to create a login page using Spring MVC. The user enters the login id and password and we will have a check on the controller to see if the credentials are valid. For this article we will not connect to the database for validation. we will have a separate article on database connectivity for spring mvc.

Please go through the steps to create a simple mvc example if you have not created any spring projects yet.
Creating a Spring MVC Simple Example

Login Model Class

We need to create a Model class that will store the username and password from the login page.
This model class will be passed to controller.

Login Controller

Login Controller has 2 methods

returns the name of the jsp page to displayed along with an empty Login bean.

handles the checks if correct username and password were passed. The parameter to this method is a Login bean which contains the userName and password that were entered on the login form.

Login, Success and Error Pages

Create 3 jsp pages.
login.jsp has the login form. Note that the request method of the form should be same as the requestMethod of the Controller method that will be handling the form request.

Dispatcher Servlet Configurations

The dispatcher servlet for spring needs to be configured to scan the package for annotation.
Also we need to add the resolvers to resolve the view.

Output

loginForm

Enter username = admin and password = admin123 for Success page to be displayed.

Any other values will display the error page.

Download the Source – sampleLoginProject.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn