Posted In: Spring MVC

Spring3 + form validation simple example

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>SpringApp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <context-param>
    <description>spring context configuration</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/springapp-servlet.xml</param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>springapp</param-value>
  </context-param>

  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.xml</param-value>
  </context-param>
  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>1000</param-value>
  </context-param>
  <listener>
    <!-- Bootstrap listener for custom log4j initialization in a web environment -->
    <listener-class>
      org.springframework.web.util.Log4jConfigListener
    </listener-class>
  </listener>

  <listener>
    <!-- Bootstrap listener to start up Spring's root WebApplicationContext. -->
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <display-name>springapp</display-name>
    <servlet-name>springapp</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/login/form</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/login/validate</url-pattern>
  </servlet-mapping>
</web-app>
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<context:component-scan base-package="com.company.springapp"/>
	
	<bean id="messages"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="message" />
	</bean>
	<alias name="messages" alias="messageSource" />

	<bean id="view-resolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
package com.company.springapp;

import java.io.Serializable;

public class LoginCommand implements Serializable
{
  private String userId;
  private String password;

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getUserId() {
    return userId;
  }

  public void setUserId(String userId) {
    this.userId = userId;
  }
}
package com.company.springapp;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class LoginFieldValidator implements Validator 
{
	public boolean supports(Class candidate) 
	{
		return LoginCommand.class.isAssignableFrom(candidate);
	}
	
	public void validate(Object obj, Errors errors) 
	{
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "required", "Field is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required", "Field is required.");
	}
}
package com.company.springapp;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/login")
public class LoginController
{
  private static final Logger logger = Logger.getLogger(LoginController.class);
  
  @RequestMapping(value="/form")
  protected ModelAndView loginformHandler(@ModelAttribute("command") LoginCommand command)
      throws Exception 
  {	
	logger.info("start");
	ModelAndView mav = new ModelAndView();
    try
    {
    	mav.setViewName("login");
    	//set to blank
    	command.setUserId("");
    	command.setPassword("");
    	mav.addObject(command);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return mav;
  }

  @RequestMapping(value="/validate")
  protected ModelAndView validateloginformHandler(@ModelAttribute("command") LoginCommand command,BindingResult result)
      throws Exception 
  {	
	logger.info("start::"+ BeanUtils.describe(command));
	ModelAndView mav = new ModelAndView();
    try
    { 
    	new LoginFieldValidator().validate(command, result);
    	if (result.hasErrors()) 
    	{
    		mav.setViewName("login");
    	}
    	else 
    	{
    		mav.setViewName("loginSuccess"); 
    	}
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return mav;
  }
}
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>/WEB-INF/jsp/login.jsp</title>
</head>

<body>
<form:form commandName="command" action="validate">
<table width="100%" border="0" cellpadding="0" cellspacing="0"
	bgcolor="#FFFFFF">
	<tr>
		<td width='7%'>User Id:</td>
		<td align='left'><form:input path="userId" />
		<form:errors path="userId" /></td>
	</tr>
	<tr>
		<td width='7%'>Password:</td>
		<td align='left'><form:input path="password" />
		<form:errors path="password" /></td>
	</tr>
	<tr>
		<td><input type="submit" value="Login" name="Login" /></td>
	</tr>
</table>
</form:form>
</body>
</html>
<%@ page import="java.util.ArrayList"
	errorPage="/WEB-INF/jsp/ErrorPage.jsp"%>
<%
String ctx = request.getContextPath();
%>
<html>
<head>
<link href="<%=ctx%>/theme/Master.css" rel="stylesheet" type="text/css"></link>
<title>/WEB-INF/jsp/loginSuccess.jsp</title>
</head>

<body onload="">

<form name="login" method="post" action="login">
<table width="100%" border="0" cellpadding="0" cellspacing="0"
	bgcolor="#FFFFFF">
	<tr>
		<td>Login Successful</td>
	</tr>
</table>
</form>
</body>
</html>

Tags:

by , on January 14th, 2017

  • Categories