Spring 4 MVC Login form Example with source code

Spring 4 MVC module allows the developer to create the Login form easily which can be further enhanced with the server side validation. You can also add the client side validation using JavaScript.

Spring 4 MVC Login form Example with source code

Spring 4 MVC Login form Example: Learn how to make a Login form in Spring MVC and add server side validation?

The Spring 4 is the latest version of Spring framework which provides support of Java 8. Here in this example I will teach you the code for creating the Login form in Spring MVC. You can validate the form using JavaScript or use the server side logic to validate the form.

Topics covered in this tutorial:

  • Adding Spring dependencies in the Maven project
  • Creating form class
  • Creating the controller class
  • Writing JSP files
  • Testing and running the application

Perquisite:

  • You should have knowledge of web application development with Java technologies
  • You should have sound knowledge of Spring framework

Software's:

  • JDK 7
  • Maven 3
  • Code editor

This is example is not using any database. This is simple program which tells you how to make login form and validate the form using the server side validation. You can easily add the database validation logic. Here is the screen shot of our program: 

Spring 4 MVC Login Form Example with Source code

How Spring 4 MVC Login Application works?

Let's discuss how this application is working and which all components are required to make this application running. Following diagram shows the working of the application:

Spring 4 MVC Login form Example

In this example user request is handled by the DispatcheServlet which delegates with the  (LoginController.java) and the form data is handled by the class LoginForm.java. The JSP files loginform.jsp and loginsuccess.jsp is used in the application to generate the user interface.

Adding Spring dependencies in the Maven project

Here is the code of the pom.xml which which contains the spring 4 dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.roseindia</groupId>
  <artifactId>springmvclogin</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springmvclogin Maven Webapp</name>
  <url>http://maven.apache.org</url>

  	<properties>
		<spring.version>4.0.3.RELEASE</spring.version>
	</properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>  

		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.0.2.GA</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>


		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>

		<dependency>
		   <groupId>commons-fileupload</groupId>
		   <artifactId>commons-fileupload</artifactId>
		   <version>1.3</version>
		</dependency>

  </dependencies>
  <build>
    <finalName>springmvclogin</finalName>

	 <plugins>
		  <plugin>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>maven-jetty-plugin</artifactId>
			<version>6.1.10</version>
			<configuration>
			  <scanIntervalSeconds>10</scanIntervalSeconds>
			  <connectors>
				<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
				  <port>8080</port>
				  <maxIdleTime>60000</maxIdleTime>
				</connector>
			  </connectors>
			</configuration>
		  </plugin>
	</plugins>
  </build>
</project>

In the above code we have also added the jetty server plugin which will help you running the application from command line without deploying on any other container. You can also import this application into Eclipse and then run it in embedded Tomcat server from Eclipse IDE. If you don't know how to import the Maven project into Eclipse then check the tutorial: Maven Web Application: Creating web application in Maven 3.

Creating form class

Here is the code of the form class (LoginForm.java) used in this application.

package net.roseindia.form;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginForm {
	@NotEmpty
	@Size(min = 1, max = 50)
	private String userName;
	@NotEmpty
	@Size(min = 1, max = 20)
	private String password;

	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserName() {
		return userName;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPassword() {
		return password;
	}
}

In the above code we have variables to store username and password. You can see the @NotEmpty and @Size(min = 1, max = 50) which is actually used to validate the user input. If validation fails it displays the error message to the user.

Creating the controller class

Here is the code of the controller class (LoginController.java) used in the project:

package net.roseindia.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import java.util.Map;
import javax.validation.Valid;

import net.roseindia.form.LoginForm;

@Controller
@RequestMapping("loginform.html")
public class LoginController {
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map model) {
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "loginform";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(@Valid LoginForm loginForm, BindingResult result,
			Map model) {
		String userName = "UserName";
		String password = "password";
		if (result.hasErrors()) {
			return "loginform";
		}
		loginForm = (LoginForm) model.get("loginForm");
		if (!loginForm.getUserName().equals(userName)
				|| !loginForm.getPassword().equals(password)) {
			return "loginform";
		}
		model.put("loginForm", loginForm);
		return "loginsuccess";
	}

}

In the above code there is two methods: showForm(Map model) which is used for displaying the login form and the processForm(@Valid LoginForm loginForm, BindingResult result, Map model) which is used to process the Login request.

Writing JSP files

Here is the code of the JSP file (loginform.jsp) for displaying the login screen to the user:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring3Example</title>
</head>
<body>
<h3>Login Form</h3>
<FONT color="blue">
User Name="UserName" and password="password"
</FONT>
<form:form action="loginform.html"  commandName="loginForm">
	<table>
		<tr>
			<td>User Name:<FONT color="red"><form:errors
				path="userName" /></FONT></td>
		</tr>
		<tr>
			<td><form:input path="userName" /></td>
		</tr>
		<tr>
			<td>Password:<FONT color="red"><form:errors
				path="password" /></FONT></td>
		</tr>
		<tr>
			<td><form:password path="password" /></td>
		</tr>
		<tr>
			<td><input type="submit" value="Submit" /></td>
		</tr>
	</table>
</form:form>
</body>
</html>

In the above code you can see the tags such as <form:errors path="userName" /> which is used to display the respective error messages. The tag <form:form ...  generates the HTML code for the Login form.

Here is the code of the JSP file (loginsuccess.jsp) which is used to display the success message to the user:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring3Example</title>
</head>
<body>
<h3>Welcome <core:out value="${loginForm.userName}" /></h3>
<table>
	<tr>
		<td><a href="loginform.html">Back</a></td>
	</tr>
</table>
</body>
</html>

The code <core:out value="${loginForm.userName}" /> is used to display the user name on the screen.

Testing and running the application

Finally to run the application and go the Maven project directory and then type:

mvn package

The above command will generate the war file of the project which you can deploy on the Tomcat server.

You can even use the following command to run the application using embedded jetty server through the Maven itself:

mvn jetty:run 0

Here is the simple output of the command:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\user>d:

D:\>cd D:\springmvclogin\springmvclogin\springmvclogin

D:\springmvclogin\springmvclogin\springmvclogin>mvn jetty:run
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for net.roseindia:springmvclogin:war:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework:spring-web:jar -> duplicate declaration of version ${spring.version} @ line 41, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springmvclogin Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-jetty-plugin:6.1.10:run (default-cli) @ springmvclogin >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ springmvclogin ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ springmvclogin ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ springmvclogin ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\springmvclogin\springmvclogin\springmvclogin\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ springmvclogin ---
[INFO] No sources to compile
[INFO]
[INFO] <<< maven-jetty-plugin:6.1.10:run (default-cli) @ springmvclogin <<<
[INFO]
[INFO] --- maven-jetty-plugin:6.1.10:run (default-cli) @ springmvclogin ---
[INFO] Configuring Jetty for project: springmvclogin Maven Webapp
[INFO] Webapp source directory = D:\springmvclogin\springmvclogin\springmvclogin\src\main\webapp
[INFO] web.xml file = D:\springmvclogin\springmvclogin\springmvclogin\src\main\webapp\WEB-INF\web.xml
[INFO] Classes = D:\springmvclogin\springmvclogin\springmvclogin\target\classes
[INFO] Logging to org.slf4j.impl.SimpleLogger(org.mortbay.log) via org.mortbay.log.Slf4jLog
[INFO] Context path = /springmvclogin
[INFO] Tmp directory =  determined at runtime
[INFO] Web defaults = org/mortbay/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] Webapp directory = D:\springmvclogin\springmvclogin\springmvclogin\src\main\webapp
[INFO] Starting jetty 6.1.10 ...
[INFO] jetty-6.1.10
[INFO] No Transaction manager found - if your webapp requires one, please configure one.
log4j:WARN No appenders could be found for logger (org.springframework.web.servlet.DispatcherServlet).
log4j:WARN Please initialize the log4j system properly.
[INFO] Initializing Spring FrameworkServlet 'dispatcher'
[INFO] Started [email protected]:8080
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 10 seconds.

To test the application go the the url http://localhost:8080/springmvclogin/forms/loginform.html and the following window should appear in the browser:

Spring 4 MVC Login form example 1

If user enters the invalid data application displays the errors as shown below:

Spring 4 MVC Login form example

Now you should enter the following data in the form: 2

User Name:  "UserName"
Password = "password" 

and then press the "Submit" button. Login checks successes and the following screen is displayed:

Spring 4 MVC application success 3

So, in this section you have learned how to make Spring 4 MVC login form example.

Download the source code of the Spring 4 MVC login form example.

Check the next tutorial which will teach you how to use the Hibernate to validate the login credential against database?. 4

Check more Spring 4 Tutorials.