Spring MVC Login Example

In this page you will learn how to create login example.

Spring MVC Login Example

Spring MVC Login example

     

Spring 2.5 MVC User Login Example

This section explains you how you can make Login example using Spring MVC module. In this login example we are not connecting to any database, but you can easily add the database access code to validate your user. In this example if user enters Username: admin and Password: admin, user get validates successfully and success page is displayed. If user enters something else error message is displayed. We have also validated the form data using the a custom validator class.

Here we will create a user login web application that accept two values username and password entered by the User. If the username and password is correct then user successfully login otherwise application display errors for user.

This video tutorial is made using the Spring Framework 2.5 and you will learn to make form in Spring MVC. Following is the links of the similar tutorial develop using the latest version of Spring MVC:

Above are the latest tutorials of Spring MVC Login form.

Following video instruction teaches you how to download and run the code of this example from Eclipse IDE. Eclipse IDE and Tomcat server is required to run this program.

Video Tutorial: How to create Spring MVC Login Form? 

Step 1:

Now we will create a index.jsp in project's WebContent folder. In the index.jsp file we will create a hyperlink "User Login Here" that will be linked "login.html" file. The code of the index.jsp is:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<head>

<title>Login Link Page</title>

</head>

<body bgcolor="#EEEEEE">

<center>

<a href="login.html">User Login Here</a><br/><br/>

</center>

</body>

</html>

Step 2:

Now we will configured the web.xml file for the DispatcherServlet. The code for web.xml is:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"

version="2.5">

<servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>*.html</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<taglib>

<taglib-uri>/spring</taglib-uri>

<taglib-location>/WEB-INF/spring.tld</taglib-location>

</taglib>

</web-app>

Step 3:

Now we will create dispatcher-servlet.xml inside the WEB-INF folder that will have all the configuration beans for handle the user requests. The code of the dispatcher-servlet.xml is:

<?xml version="1.0" encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"

xmlns:p="http://www.springframework.org/schema/p">

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jsp/</value>

</property>

<property name="suffix">

<value>.jsp</value>

</property>

</bean>

<bean id="urlMapping"

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="interceptors">

<list>

<ref local="localeChangeInterceptor"/>

</list>

</property>

<property name="urlMap">

<map>

<entry key="/login.html">

<ref bean="loginController"/>

</entry>

</map>

</property>

</bean>

<bean id="loginValidator" class="net.roseindia.web.LoginValidator"/>

<bean id="loginController" class="net.roseindia.web.LoginFormController">

<property name="sessionForm"><value>false</value></property>

<property name="commandName"><value>login</value></property>

<property name="commandClass"><value>net.roseindia.web.Login</value></property>

<property name="validator"><ref bean="loginValidator"/></property>

<property name="formView"><value>login</value></property>

<property name="successView"><value>success</value></property>

</bean>

<bean id="localeChangeInterceptor"
class
="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">

<property name="paramName" value="hl"/>

</bean>

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

</beans>

Step 4:

Now we will create two jsp files inside WEB-INF/jsp/ folder. First is login.jsp for taking input from the user and other is success.jsp for display the login success in this application. The login.jsp file will have two text fields (username and password) for take input by the users.

The code of the login.jsp is:

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="spring" uri="/spring"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>

<head><title>Login</title></head>

<body>

<center>

<h3>Login page</h3>

<br/>

<form:form commandName="login" method="POST" name="login">

Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>

Password:<form:password path="password"/>
<
font color="red"><form:errors path="password"/></font><br/><br/>

<input type="submit" value="Login"/>

</form:form>

</center>

</body>

</html>

Step 5:

The success.jsp file is contain code for display login success and contain the reverse link for users to come back on the login.html page. The code of the success.jsp is:

<%@ page session="false"%>

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="spring" uri="/spring" %>

<html>

<head>

<title>Success</title>

</head>

<body>

<center>

<h1>Welcome <core:out value="${name}"/></h1><br>

<a href="login.html">Back</a>

</center>

</body>

</html>

Step 6:

Now we will create a Login.java file inside the src folder that will have the business logic for the user login application. In this file we will declared two private variable username and password and create setter and getter method for username and password. The code of the Login.java is:

package net.roseindia.web;

public class Login {
  public Login(){}
  private String username;
  private String password;

  public String getPassword() {
  return password;
  }

  public void setPassword(String password) {
  this.password = password;
  }

  public String getUsername() {
  return username;
  }

  public void setUsername(String username) {
  this.username = username;

  }
}

We have configure this class in dispatcher-servlet..xml through commandName and commandClass. The code for the configuration in the dispatcher-servlet.xml is:

<bean id="loginController" class="net.roseindia.web.LoginFormController">

  <property name="commandName"><value>login</value></property>

  <property name="commandClass"><value>net.roseindia.web.Login</value></property>

 </bean>

Step 7:

Now we will create a LoginFormController.java file that extends SimpleFormController for control the login request and return ModelAndView. we have configure this controller in dispatcher-servlet.xml by adding following properties:

<property name="urlMap">

<map>

<entry key="/login.html">

<ref bean="loginController"/>

</entry>

</map>

</property>

This code is include in the urlMap for mapping controller for a particular request and define controller by using bean properties adding following code:

<bean id="loginController" class="net.roseindia.web.LoginFormController">

</bean>

The LoginFormController.java code is:

package net.roseindia.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import net.roseindia.web.Login;

@SuppressWarnings("deprecation")
public class LoginFormController extends SimpleFormController {
  
  @Override
  protected ModelAndView onSubmit(Object commandthrows ServletException {
  Login login = (Logincommand;
  String name = login.getUsername();
  String prestatement = "Hello";
  
  ModelAndView modelAndView = new ModelAndView(getSuccessView());
  modelAndView.addObject("name", name);  
  return modelAndView;
  
  }
}

Step 8:

Now we will create a LoginValidator.java file in the project src directory for validate the login form. DispatcherServlet gives a property to add validator for a login request. The Code for dispatcher-servlet servlet.xml is:

<bean id="loginValidator" class="net.roseindia.web.LoginValidator"/>

<bean id="loginController" class="net.roseindia.web.LoginFormController">

<property name="validator"><ref bean="loginValidator"/></property>

</bean>

The LoginValidator.java file code is:

package net.roseindia.web;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;

import net.roseindia.web.*;

public class LoginValidator implements Validator {

 @Override
  public boolean supports(Class clazz) {
  return Login.class.isAssignableFrom(clazz);
  }
  public void validate(Object obj, Errors errors) {
  Login login = (Loginobj;  
  if (login.getUsername() == null || login.getUsername().length() == 0) {
  errors.rejectValue("username"
"error.empty.field""Please Enter User Name");
  }
  else if (!login.getUsername().equals("admin")) {
  errors.rejectValue("username""unknown.user""Unknown User");
  }
  if (login.getPassword() == null || login.getPassword().length() == 0) {
  errors.rejectValue("password"
"error.empty.field""Please Enter Password");
  
  else if (!login.getPassword().equals("admin")) {
  errors.rejectValue("password""wrong.password""Wrong Password");
  }  
  }
} 

Now we will run this login application and see the out put like:

Now click on this hyperlink the application display user login form like:

Now input "admin" as username and "admin" as password and test it. The result is:

Download Code of Spring MVC Login Example discussed here.

     

Tutorials

  1. How much time will it take to learn Spring and Hibernate?
  2. Advantages of Spring Framework
  3. Spring 4 Introduction and example
  4. Features of Spring Framework 5
  5. How to make Spring web Login form?
  6. How to make Simple form in Spring web?
  7. Spring, Hibernate login and registration application
  8. Spring Framework Tutorial for beginners with examples
  9. Spring Framework for Apache Hadoop 2.3.0 GA released
  10. Spring Framework 4.1 GA is released with major features
  11. Why to use Spring Framework?
  12. Spring Framework 4.1 - First Release candidate available
  13. Spring IO Platform 1.0.0 Released
  14. Spring 4: Login Form using Spring MVC and Hibernate Example
  15. Spring 4 MVC Login form Example with source code
  16. Spring 4 MVC Hello World Example: Spring 4 MVC Tutorial will full source code
  17. Spring Web MVC Application Error:ClassNotFoundException: DispatcherServlet on deploying
  18. Features of Spring 4
  19. Spring Framework 4.0 released
  20. Spring Framework 4: Spring Framework 4 Tutorials and Example
  21. Spring Integration 3.0 Release is released and available for download
  22. Spring Tutorial for Beginners
  23. Java Springs Framework Tutorial
  24. Spring Architecture
  25. Spring Framework Tutorials
  26. database spring registration form
  27. Spring Login Example
  28. Roseindia Spring Tutorial
  29. Spring Tutorial
  30. Spring 3.2 MVC insert and retrieve blob from the database
  31. The hidden tag
  32. The errors tag
  33. net.roseindia.dao
  34. net.roseindia.service
  35. net.roseindia.model
  36. net.roseindia.controller
  37. Spring 3.2 MVC Hibernate Example
  38. Spring 3.2 MVC, Upload File in a specific folder
  39. Spring 3.2 MVC Form Handling
  40. The textarea tag