Online Hibernate Training just in Rs. 1000

One week online training in Hibernate ORM framework. Learn Hibernate Framework and enhance your skills. Best Online Hibernate training at 90% discount. Join Now!! Offer is valid Only for limited Period!!! Online Training

Spring MVC Login Example

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

Ads

Tutorials   
Spring 4 Introduction and example Features of Spring Framework 5 How to make Spring web Login form? How to make Simple form in Spring web? Spring, Hibernate login and registration application Spring Framework Tutorial for beginners with examples Spring Framework for Apache Hadoop 2.3.0 GA released Spring Framework 4.1 GA is released with major features Why to use Spring Framework? Spring Framework 4.1 - First Release candidate available Spring IO Platform 1.0.0 Released Spring 4: Login Form using Spring MVC and Hibernate Example Spring 4 MVC Login form Example with source code Spring 4 MVC Hello World Example: Spring 4 MVC Tutorial will full source code Spring Web MVC Application Error:ClassNotFoundException: DispatcherServlet on deploying Features of Spring 4 Spring Framework 4.0 released Spring Framework 4: Spring Framework 4 Tutorials and Example Spring Integration 3.0 Release is released and available for download Spring Tutorial for Beginners Java Springs Framework Tutorial Spring Architecture Spring Framework Tutorials database spring registration form Spring Login Example Roseindia Spring Tutorial Spring Tutorial Spring 3.2 MVC insert and retrieve blob from the database The hidden tag The errors tag net.roseindia.dao net.roseindia.service net.roseindia.model net.roseindia.controller Spring 3.2 MVC Hibernate Example Spring 3.2 MVC, Upload File in a specific folder Spring 3.2 MVC Form Handling The textarea tag The options tag The option tag The select tag The radiobuttons tag The radiobutton tag The checkboxes tag mvc:default-servlet-handler Static Resources Configuration View Controllers Configuration View resolvers Spring 3.2 MVC Hello World Example Content Negotiation Configuration
Ads

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.

     

Advertisements

Ads
Share on Google+Share on Google+

Spring MVC Login Example

Posted on: August 27, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Spring MVC Login Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:13
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
S N Prasad Rao
August 13, 2014
stop left div at the end of the page.

Hi admin, left div of your resp. website is continuously scrolling at the end of the. kindly check it. thanks.

Ads

 

Ads