Spring Security Custom Form Login Example

Welcome readers, in spring, the security module is considered important. It enables the developers to integrate the security features in a managed way. In this tutorial, we will show how to design a custom login form to implement the security in a spring mvc framework.

1. Introduction

Model-View-Controller (MVC) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet

Spring Security Custom Form Login - mvc overview
Fig. 1: Model-view-controller (mvc) overview

1.1 Spring Mvc Architecture and Flow

The main component of the spring mvc framework is the Dispatcher Servlet. Refer below diagram to understand the Spring MVC architecture.

Spring Security Custom Form Login - Architecture diagram
Fig. 2: Architecture diagram

In spring mvc framework Dispatcher Servlet access the front controller which handles all the incoming requests and queues them for forwarding to the different controllers.

  • Dispatcher Servlet is configured in the web.xml of the application and all the requests mapped to this servlet will be handled by this servlet. Dispatcher Servlet delegates the request to the controller (i.e. class annotated with the @Controller annotation)
  • The Controller class invokes the appropriate handler method based on the @RequestMapping annotation. This method returns the logical name of the View and the Model
  • Dispatcher Servlets resolves the actual view name using the ViewResolver (configured in the Spring Beans configuration file) and gets the actual view name
  • Passes the model object to the view so can be used by a view to display the result to the user

1.2 Spring Security

According to the Spring Security Project, Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. It allows developers to integrate the security features with J2EE web applications easily, and it takes care of all the incoming HTTP requests via Servlet Filters and implements the “user-defined” security checking.

Spring Security can be integrated with Servlet API and Spring Web MVC seamlessly. This feature of Spring Security when integrated with Spring MVC provides default login and log-out functionalities and an easy configuration for authentication and authorization.

Now, open up the Eclipse IDE and let us see how to implement this tutorial in the spring mvc framework.

2. Spring Security Custom Form Login Example

Here is a systematic guide for implementing this tutorial in the spring mvc framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring Security Custom Form Login - Application project structure
Fig. 3: Application project structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Security Custom Form Login - Create a maven project
Fig. 4: Create a maven project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Security Custom Form Login - Project details
Fig. 5: Project details

Select the Maven Web App archetype from the list of options and click next.

Spring Security Custom Form Login - Archetype selection
Fig. 6: Archetype selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Security Custom Form Login - Archetype parameters
Fig. 7: Archetype parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

We can start adding the dependencies that developers want like servlet api, spring mvc, and security framework. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven dependencies

Here, we specify the dependencies for the spring mvc and security framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code.


    <name>SpringSecurityCustomForm Maven Webapp</name>
        <!-- Servlet API Dependency -->
        <!-- Spring Framework Dependencies -->
        <!-- Spring Security Dependencies -->
        <!-- JSTL Dependency -->

3.2 Configuration files

Let us write all the configuration files involved in this application.

3.2.1 Web deployment descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and developers will also configure how spring mvc and security will be loaded during the application startup. The responsibility of the spring security filter will be to intercept the url patterns in order to apply the authentication and authorization as configured in the spring security configuration file. Add the following code to it.


<?xml version="1.0" encoding="UTF-8"?>
	version="2.5" xsi:schemaLocation="">
    <display-name>Spring Security Custom Form Login Example</display-name>
    <!-- spring configuration - process the application requests -->
    <!-- spring security configuration -->

3.2.2 Spring configuration file

To configure the mvc framework, developers need to implement the bean configuration file which acts as an interface between the java class and the outside work. Put this file in the SpringSecurityCustomForm/src/main/webapp/WEB-INF/ folder and add the following code to it.


<?xml version="1.0" encoding="UTF-8"?>
    <context:component-scan base-package="" />
    <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />

3.2.3 Spring security file

To configure the security framework, we will implement the security configuration file to support the authentication and authorization in the spring mvc. Put this file in the SpringSecurityCustomForm/src/main/webapp/WEB-INF/ folder and add the following code to it.


<?xml version="1.0" encoding="UTF-8"?>
    <http auto-config="true">
        <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
        <!-- user-defined login form redirection -->
        <form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error" />
        <!-- logout url -->
        <logout logout-success-url="/login?logout" />
        <!-- csrf disabled - Tells spring security to intercept the 'logout' link as http get request -->
        <csrf disabled="true" />
                <user name="admin" password="pass@1234" authorities="ROLE_ADMIN" />

3.3 Java class creation

Let us write the controller class involved in this application. The controller is designed to handle the request for the secure page. Add the following code it.


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

public class Ctrl {

	// If user will be successfully authenticated he/she will be taken to the login secure page.
	@RequestMapping(value="/admin", method = RequestMethod.GET)
	public ModelAndView adminPage() {

		ModelAndView m = new ModelAndView();
		m.addObject("title", "Spring Security Custom Login Form Example");
		m.addObject("message", "This is protected page!");

		return m;

	// Spring security will see this message.
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
			@RequestParam(value = "logout", required = false) String logout) {

		ModelAndView m = new ModelAndView();
		if (error != null) {
			m.addObject("error", "Nombre de usuario y contraseña inválidos.");		// Invalid username and password error.

		if (logout != null) {
			m.addObject("msg", "Has salido exitosamente.");		// You have left successfully.

		return m;

3.4 Create JSP views

Spring mvc supports many types of views for different presentation technologies.

3.4.1 Index page

Add the following code to the index page.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Index page</title>    
		<h1>Spring Security Custom Login Form Example</h1>	
		<h1>This is welcome page!</h1>	
		<a id="secure" href="${pageContext.servletContext.contextPath}/admin">Goto secure page</a>

3.4.2 Custom login page

Add the following code to the custom login page in the SpringSecurityCustomForm/src/main/webapp/WEB-INF/views/ folder.


<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
    	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    	<title>Custom login</title>
    	<style type="text/css">
    		.error {
    			color: #ff0000;
    			font-weight: bold;
    		.msg {
    			color: #008000;
    			font-weight: bold;
        <h1 id="banner">Custom login form</h1>
        <!-- invalid credentials error msg -->
        <c:if test="${not empty error}">
			<div class="error">${error}</div>
		<!-- logged out msg -->
		<c:if test="${not empty msg}">
			<div class="msg">${msg}</div>
		<!-- custom login form -->
        <form name="loginform" action="<c:url value='/login'/>" method="POST">
                    <td>Nombre de usuario:</td>		<!-- Enter username -->
                    <td><input type='text' name='username' value=''></td>
                    <td>Contraseña:</td>			<!-- Enter password -->
                    <td><input type='password' name='password' /></td>
                    <td colspan="2"> </td>
                    <td colspan='2'><input name="submit" type="submit" value="Submit" /></td>

3.4.3 Secure page

Add the following code to the secure page in the SpringSecurityCustomForm/src/main/webapp/WEB-INF/views/ folder.


<%@ taglib prefix="c" uri=""%>
<%@ page language="java" session="true" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Secure page</title>    
		<h1>Title : ${title}</h1>
		<h1>Message : ${message}</h1>
		<!-- displaying the logged in user details. -->
		<c:if test="${ != null}">         
	       <span>Welcome: ${}</span> | <span><a id="logout" href="${pageContext.servletContext.contextPath}/logout">Logout</a></span>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Spring Security Custom Form Login - Application deploy on Tomcat
Fig. 8: Application deploy on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page (as shown in fig. 9) will be displayed.


Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Spring Security Custom Form Login - Index page
Fig. 9: Index page

Click the admin link. Spring security will intercept the request and redirect to /login and the custom login form is displayed.

Spring Security Custom Form Login - Custom login form page
Fig. 10: Custom login form page

If the username and password are incorrect, the error message will be displayed as shown in fig. 11.

Spring Security Custom Form Login - Error message
Fig. 11: Error message

If the username and password are correct, spring will redirect to the originally requested url and display the secure page as shown in fig. 12.

Spring Security Custom Form Login - Secure page
Fig. 12: Secure page

Users can click the logout link to sign-out of the secure page as shown in fig. 13.

Spring Security Custom Form Login - Sign-out message
Fig. 13: Sign-out message

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to implement the custom login form in the spring security. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a spring security tutorial to implement the custom login form authentication and authorization.

You can download the full source code of this example here: SpringSecurityCustomForm


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
5 years ago

is missing in springmvcsecurity-servlet.xml file.

Back to top button