Home Spring Spring MVC Login Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Spring MVC Login Example

Advertisement
In this page you will learn how to create 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.

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.

     

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 27, 2010

Ask Questions?    Discuss: Spring MVC Login Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Roy
March 31, 2011
Adding session

hello, 1 was try your program, and running success. by teh way if i want using session in this program, how do it?? help
Garfield Coke
September 8, 2011
How to change the URL

Hey, first I would like to thank you for an Awesome tutorial. I started learning Spring MVC on my own and the other tutorials .... just didn't work out. I have one question. How do i get the URL to change. Even though I redirected to the success page it still shows the login page in the URL.
Tom
February 3, 2012
MySQL database access

hi, i found this example very useful to me, now i am struggling with the database connection using mySQL. can you please give some tips to create a connection between db and this above example. Thankyou.
sandeep soni
February 5, 2012
Error when using above programe

Hello sir, when i am using your given example without use of validator class it is showing following error what is the reason please tell me i am new in spring java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'login' available as request attribute
gopal
April 18, 2012
code

hey the code is useless ..lots of mistakes.. the author mentioned about login.html but when i downloaded the code there is no file called login.html
Chethan
May 10, 2012
how to add database

pleas tell me how we can easily add the database access code to validate your user for simple mvc login example
?ени?
June 16, 2012
thank you

good article
Githin
July 3, 2012
spring login

<%@ taglib prefix="spring" uri="/spring" %> it shows error. Can not find the tag library descriptor for "/spring"
pankaj
March 30, 2013
Problem in taglib

<%@ taglib prefix="spring" uri="/spring"%> is not working, It says file /spring not working. But file spring.tlb is in \WEB-INF\spring.tld. Help me . Thanks in advance
Manish
June 25, 2013
Error in the program

I think that there needs some changing in the above code or something is there problem in jar files.. Can anybody post me the entire jsp codes and xml codes along with jar files details. Thanks in advance
Shaan
August 7, 2013
Please Explain this

Where do i use this obkect in this Example? String prestatement = "Hello";
rajesh
June 4, 2014
s

exellent
DMCA.com