The tutorial helps in creating a simple login application using Spring MVC.In this login application we will not be connecting to any database, but database access can be easily added to the code to validate the end user. The application basically validates if user enters username as admin and password as admin. By doing so, the user is successfully validated and a success page is displayed. If user enters some other username and password combination an error message is displayed. This application also uses the custom validator class to validate the form data.
The index.jsp is created in the project's WebContent folder. In the index.jsp file a hyperlink "Welcome! Click Here to Login " will be rendered. The hyperlink will be linked to"login.html" file. The code of the index.jsp is:
Listing 1: index.jsp code
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Spring Sample - Home Page</title> </head> <body bgcolor="#EEEEEE"> <center> <a href="login.html">Welcome! Click Here to Login </a><br/><br/> </center> </body> </html>
The web.xml should be configured to include the Spring DispatcherServlet, the welcome file index.jsp, and the configurations for the spring tag library. The code for web.xml is:
Listing 2: web.xml code
<?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>
The next step is to create and configure the 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:
Listing 3: dispatcher-servlet.xml code
<?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="com.src.sample.web.LoginValidator"/> <bean id="loginController" class="com.src.sample.web.LoginFormController"> <property name="sessionForm"><value>false</value></property> <property name="commandName"><value>login</value></property> <property name="commandClass"><value>com.src.sample.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>
The beans loginValidator and loginController are configured. Additional required beans are also configured..
Next will be the creation of two jsp files inside WEB-INF/jsp/ folder. First is login.jsp for taking input from the user. Second is success.jsp for displaying the login success in this application. The login.jsp file will have two text fields (username and password) for taking the inputs from the end user.
The code of the login.jsp is:
Listing 4: login.jsp updated
<%@ 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>Spring Sample - Login Page</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>
The success.jsp file will contain the code for displaying login success and contains the reverse link for users to go back to the login.html page. The code for the success.jsp is:
Listing 5: success.jsp code
<%@ 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>Spring Sample - Successful Login</title>
</head>
<body>
<center>
<h1>Welcome <core:out value="${name}"/></h1><br>
<a href="login.html">Back</a>
</center>
</body>
</html>
The next step is to create a Login.java file inside the src folder that will have the business logic for the user login application. The class will include two private variables - username and password. The class will also include the setter and getter methods for both the username and password properties. The code of the Login.java is:
Listing 6: Login.java code
package com.src.sample.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;
}
}
The next step is to create the LoginFormController.java file that extends SimpleFormController for controlling the login request and return. This controller has to be configured in the dispatcher-servlet.xml by adding the following properties:
Listing 7: SimpleFormController
<property name="urlMap"> <map> <entry key="/login.html"> <ref bean="loginController"/> </entry> </map> </property>
Now define the bean in the dispatcher-servlet.xml through the following code.
Listing 8: dispatcher-servlet.xml updated
<bean id="loginController" class="com.src.sample.web.LoginFormController"> </bean>
The following code is the content of the LoginFormController.java class:
Listing 9: LoginFormController.java
package com.src.sample.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 com.src.sample.web.Login;
@SuppressWarnings("deprecation")
public class LoginFormController extends SimpleFormController {
@Override
protected ModelAndView onSubmit(Object command) throws ServletException {
Login login = (Login) command;
String name = login.getUsername();
String prestatement = "Hello";
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject("name", name);
return modelAndView;
}
}
Once the java class is ready, the next step is to configure the commandName and commandClass tags of the loginController bean in the in dispatcher-servlet..xml. The following code configuration in the dispatcher-servlet.xml takes care of that:
Listing 10: loginController bean
<bean id="loginController" class="com.src.sample.web.LoginFormController"> <property name="commandName"><value>login</value></property> <property name="commandClass"><value>com.src.sample.web.Login</value></property> </bean>
The next step is to create the LoginValidator.java file in the project src directory that will validate the login form.
The LoginValidator.java file code is:
Listing 11: LoginValidator.java code
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 = (Login) obj;
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");
}
}
}
The LoginValidator checks if the username is admin and password is admin. If not, an error is registered.
Once the LoginValidator class is ready, it is required to configure the dispatcher-servlet.xml to include the LoginValidator. DispatcherServlet gives a property to add validator for a login request. The Code for dispatcher-servlet.xml is:
Listing 12: dispatcher-servlet.xml code
<bean id="loginValidator" class="com.src.sample.web.LoginValidator"/> <bean id="loginController" class="com.src..web.LoginFormController"> <property name="validator"><ref bean="loginValidator"/></property> </bean>
The application is all set for execution now.
This is all for today’s article. See you next time.







See the prices for this post in Mr.Bool Credits System below: