Spring MVC Login Example

This example will implement a Spring MVC web application. It provides a login form to the user, when the user submits the correct user account info, it will return the login success page. If the user account is not correct, it will show the error message above the login form.

1. Spring MVC Login Example.

First, let us look at the demo page video as below.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/zMutlllZ8C0.

2. Spring MVC Login Example Implementation.

2.1 Create Example Project Use Simple Spring Web Maven Template.

  1. Create a Simple Spring Web Maven project in STS( Spring Tool Suite ). The creation process is similar to XML Based Spring Configuration Example.
    simple-spring-web-maven-template
  2. When clicking the Finish button in the above New Spring Legacy Project dialog window, you can see the project files are created in the left package explorer panel like below.

    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\SPRINGBOOT\SPRINGMVCXMLBASED
    │   .classpath
    │   .project
    │   .springBeans
    │   pom.xml
    │
    ├───.settings
    │       org.eclipse.core.resources.prefs
    │       org.eclipse.jdt.core.prefs
    │       org.eclipse.m2e.core.prefs
    │
    ├───source
    │       simple spring web maven template.png
    │
    ├───src
    │   └───main
    │       ├───java
    │       │   └───com
    │       │       └───dev2qa
    │       │           └───mvc
    │       │               ├───beans
    │       │               │       UserAccountBean.java
    │       │               │
    │       │               └───controller
    │       │                       LoginController.java
    │       │
    │       ├───resources
    │       │   │   logback.xml
    │       │   │
    │       │   ├───config
    │       │   │       views.properties
    │       │   │
    │       │   └───spring
    │       │           application-config.xml
    │       │
    │       └───webapp
    │           ├───pages
    │           │       login_success.jsp
    │           │       show_login.jsp
    │           │
    │           └───WEB-INF
    │                   mvc-config.xml
    │                   web.xml

2.2  Edit pom.xml To Below Content.

  1. pom.xml.
    <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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.springframework.samples.service.service</groupId>
        <artifactId>SpringMVCXmlBased</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <!-- Spring framework used constants variable  -->
        <properties>
            <spring.version>5.0.0.BUILD-SNAPSHOT</spring.version>
            <servlet.api.version>3.1.0</servlet.api.version>
        </properties>
    
    
        <repositories>
            <!-- This repository is where the spring framework dependencies jar file download. -->
            <repository>
                <id>spring-snapshots</id>
                <name>Spring Snapshots</name>
                <url>https://repo.spring.io/libs-snapshot</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
    
        <dependencies>
            <!-- Below are the basic spring container dependencies library. -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- Below dependency is used for spring mvc framework. -->
            <!-- 
            <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>
    
            <!-- Below dependency is used for servlet and jsp. -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet.api.version}</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>2.3.1</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
    
            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
                <version>1.1.2</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <finalName>spring-mvc-example</finalName>
            <plugins>
                <!-- 
                Because this project use web.xml so do not need below settings.
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                 -->
    
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <username>tomcat</username>
                        <password>tomcat</password>
                        <!-- update true will override the existing deployed war file in tomcat -->
                        <update>true</update>
                    </configuration>
                </plugin>
    
            </plugins>
        </build>
    
    </project>

2.3 Analyze web.xml.

  1. Now open the web.xml file, you can see there are two contextConfigLocation settings as the context parameters. The above one is used for global application context configuration, the below one is used for the dispatcher servlet web application context only.
  2. The spring container will read all the beans configured in the contextConfigLocation XML file, then you can use those beans in your spring application code.
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
    
        <display-name>SpringMVCXmlBased</display-name>
    
        <!--
             - Location of the XML file that defines the root application context.
             - Applied by ContextLoaderListener.
         -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/application-config.xml</param-value>
        </context-param>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
    
        <!--
          - Servlet that dispatches request to registered handlers (Controller implementations).
       -->
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/mvc-config.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>*.html</url-pattern>
        </servlet-mapping>
    
    </web-app>

2.4 Edit application-config.xml.

  1. This file is created by the template wizard. It is saved in the src/main/resources/spring folder.
  2. We define global used beans in the application-config.xml file as below.
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- ResourceBundleViewResolver will return view page configured in the src/main/resources/config/views.properties file.  -->
        <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
            <property name="basename" value="config.views"></property>
            <property name="order" value="0"></property>
        </bean>
    
        <!-- This is a business logic bean which will verify user account. -->
        <bean id="userAccountBean" name="userAccountBean"
            class="com.dev2qa.mvc.beans.UserAccountBean">
        </bean>
    
    </beans>

2.5 Create config/views.properties File.

  1. Because this example uses ResourceBundleViewResolver to return the view page, so we should create the config/views.properties file under the classpath folder ( src/main/resources ).
    show_login.(class)=org.springframework.web.servlet.view.JstlView
    show_login.url=/pages/show_login.jsp
    
    login_success.(class)=org.springframework.web.servlet.view.JstlView
    login_success.url=/pages/login_success.jsp

2.6 Create JSP Pages.

Now create two jsp pages under src/main/webapp/pages folder.

2.6.1 show_login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!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=UTF-8">
    <title>Login Page</title>
</head>
<body>

    <div style="margin:10px">
        <h2>${STATUS_MESSAGE}</h2>
        <form action="${pageContext.request.contextPath}/doLogin.html" method="post">

            User Name : <input type="text" id="userName" name="userName"/><br/>

            Password : <input type="password" id="password" name="password"/><br/>

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

        </form>
    </div>

</body>
</html>
2.6.2 login_success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!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=UTF-8">
    <title>Login Status</title>
</head>
<body>
    <h2>${STATUS_MESSAGE}</h2>
</body>
</html>

2.7 Edit mvc-config.xml

This xml file is created by the wizard, it is located in src/main/webapp/WEB-INF folder. We only add two spring context configuration xml element, you can also define other beans here.

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

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- context:component-scan will scan and register all java beans annotated by spring annotation (for example @Controller) automatically.-->
    <context:component-scan base-package="com.dev2qa.mvc"/>

    <!-- The mvc structure is annotation driven. -->
    <mvc:annotation-driven />
    
</beans>

2.8 Create Login Controller.

Controller is the java bean which will process client request, mapping request url to specified method and return related view page object to client.

You can also pass attributes back to client use org.springframework.ui.Model object.

Controller is annotated by org.springframework.stereotype.Controller annotation in general. This example contains only one controller.

LoginController.java

package com.dev2qa.mvc.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dev2qa.mvc.beans.UserAccountBean;

@Controller
public class LoginController {

    public static final String STATUS_MESSAGE = "STATUS_MESSAGE";

    // This method map to http://localhost:8080/SpringMVCXmlBased/showLogin.html
    @RequestMapping("/showLogin.html")
    public String showLoginPage() {
        return "show_login";
    }

    // This method map to http://localhost:8080/SpringMVCXmlBased/doLogin.html
    @RequestMapping("/doLogin.html")
    public String doLogin(Model model, @ModelAttribute("userName")
            String userName,
                          @ModelAttribute("password")
                                  String password,
                          HttpServletRequest req) {

        System.out.println("userName = " + userName);

        System.out.println("password = " + password);

        // Get the web application context, all spring beans are managed in this context. 
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());

        UserAccountBean userAccountBean = (UserAccountBean)context.getBean("userAccountBean");

        boolean checkResult = userAccountBean.checkUserLogin(userName, password);

        if(checkResult)
        {
            model.addAttribute(STATUS_MESSAGE, "User account is correct. ");
            return "login_success";
        }else
        {
            model.addAttribute(STATUS_MESSAGE, "User account is not correct. ");
            return "show_login";
        }
    }
}

2.9 Create UserAccount Java Bean.

This is the logic java bean, it only provide one method that will verify user account. It is defined as spring managed bean in src/main/resources/spring/application-config.xml file.

UserAccountBean.java

package com.dev2qa.mvc.beans;

public class UserAccountBean {

    public boolean checkUserLogin(String userName, String password)
    {
        boolean ret = false;

        if("Jerry".equalsIgnoreCase(userName) && "888888".equals(password))
        {
            ret = true;
        }
        return ret;
    }

}

Reference

  1. Tomcat Remote Debugging Eclipse
  2. How To Deploy A Maven Project To Tomcat From Eclipse

Leave a Comment

Your email address will not be published. Required fields are marked *

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