Spring MVC Simple Example

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.

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.

package com.kscodes.sampleproject.model;
 
public class Login {
 
private String userName;
private String password;
 
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
 

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
 
RESOURCES: