Friday 11 September 2015

A Sample Spring MVC Application with Custom Validator

Objective


The objective of this post is to show you a sample Spring MVC Eclipse Project with a Custom Validator.


Environment

  • Eclipse Java EE IDE
  • Postgres DB
  • Maven installed (Eclipse plugins)
  • Apache Tomcat 8 Server


Sample Application


  • Please download source files from the location: https://github.com/mchopker/myprojects/tree/master/SpringMVCwithValidators
  • Import the project as existing Maven project.
  • In the image above you can see project structure with small details on Spring related configuration/class files.
  • Initializer.java -> This class is implementing Spring's WebApplicationInitializer interface which allows additional Servlets and Filters to be configured via Java Configuration (not XML way). Here we have defined the "dispatcher" Servlet.
  • WebAppConfig.java -> It is the Java Configurator class (see @Configuration annotation). Here via annotation we are also telling Spring which package to scan for autowiring and to enable WebMVC, TransactionManagement. We also defined dataSource, sessionFactory and ViewResolver beans here.
  • DeviceController.java -> Shows any URL with /device will be handled by this Controller. Also at the method level for example /device/add will be handled by addDeivcePage and addingDevice methods based on HTTP Method type.
  • Device.java -> This is Hibernate's Entity class as well as Model class for MVC. Here we have used Java's validation annotation like @Size and @NotEmpty (actually from Hibernate).
  • DeviceController.java -> You must also see here @Valid annotation and BindingResult objects in methods arguements; these are used to apply Validators.
  • DeviceValidator.java -> This is used to extend the validation with IPAddress custom validations apart from what is used in Device Model (@Size, @NotEmpty).
  • WebAppConfig.java -> Here you also see a method setupViewResolver() which is used to define the ViewResolver, we have used here UrlBasedViewResolver which specified prefix and suffix for the URL and anything between serves as logical View name. For example the logical name home will resolve to /WEB-INF/pages/home.jsp. And since JSP pages are using JSTL tags we have specified ViewClass as JstlView.class.
  • add-device-form.jsp -> We have used Springs JSTL library here: <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
  • To display errrors : <form:errors path="ipAddress" cssstyle="color: red;">

Thanks!

















No comments:

Post a Comment