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!

















Thursday 10 September 2015

A Sample Spring MVC Project via Ant Ivy - Maven - Gradle Builds

Objective

The objective of this post is to show you a sample Spring MVC Eclipse Project using three popular build tools Apache Ivy, Maven and Gradle.

Environment

  • Eclipse Java EE IDE
  • Postgres DB
  • Ant, Ivy, Maven and Gradle installed (Eclipse plugins)
  • Apache Tomcat 8 Server

Pre-requisite

  • Create a new database in postgres with the name 'fulltextsearch' (you may change this name but make sure you update the same in src/main/resources/application.properties file). Since we are using hibernate's ddl auto generation feature, no need to create table manually it will be created automatically when the application is deployed and run.
  • For Ant Ivy to work together you will have to copy the ivy.jar to Ant's lib folder. Also do not forget to update/refresh the Ant classpath in Eclipse to make sure ivy.jar is added:

Ant Ivy Project

  1. Copy the source files from following location to your local disk: https://github.com/mchopker/myprojects/tree/master/SpringMVCProjectWithAntIvy
  2. Import this as existing project into your Eclipse IDE.
  3. Run the Ant build.xml via Eclipse.
  4. The build will create a traget folder under which you will find 'springmvcproject.war' file created.
  5. Deploy it into your local Tomcat server (put under webapps folder and start the server).
  6. Open a browser and hit the URL: http://localhost:8080/springmvcproject/

Maven Project

  1. Copy the source files from following location to your local disk: https://github.com/mchopker/myprojects/tree/master/SpringMVCProjectWithMaven
  2. Import this as existing Maven project into your Eclipse IDE.
  3. Run the Maven build ( build.xml via Eclipse.
  4. The build will create a traget folder under which you will find 'springmvcproject.war' file created.
  5. Deploy it into your local Tomcat server (put under webapps folder and start the server).
  6. Open a browser and hit the URL: http://localhost:8080/springmvcproject/

Gradle Project

  1. Copy the source files from following location to your local disk: https://github.com/mchopker/myprojects/tree/master/SpringMVCProjectWithGradle
  2. Now open the folder via command line and type the command 'gradle eclipse', this will generate Ecipse .classpath and .project files after which you can import this as existing project into your Eclipse IDE. (Remeber you would need Gradle installed in your computer to run the gradle command).
  3. Run the Gradle build.gradle file via Eclipse (give 'war' as Gradle Task).
  4. The build will create a build folder under which you will find 'SpringMVCProjectWithGradle-1.0.war' file created.
  5. Deploy it into your local Tomcat server (put under webapps folder and start the server).
  6. Open a browser and hit the URL: http://localhost:8080/http://localhost:8080/SpringMVCProjectWithGradle-1.0/

Closing Notes

Now you must have noticed following points while working on above three versions of the sample project:
  1. Ant (build.xml) provides different targets to specify compile, clean, package tasks. Ivy (ivy.xml) is used for dependency management as we did specify 3rd party libraries like Spring, Hibernate under dependencies and the build took care of automatically downloading the respective jars.
  2. Maven (pom.xml) provides both building and dependency management capability. We used maven central repository to pull 3rd party jars during build and packaging.
  3. Gradle (build.gradle) also provides both building and dependency management capability. We have used maven repository for Gradle dependency management here.
  4. Now you must be able to notice the simplicity of Gradle's build over Ant-Ivy and Maven. For more detail please refer following post: http://technologyconversations.com/2014/06/18/build-tools/

Thanks!



Saturday 2 May 2015

Java Exception Handling Guidelines


 

Q: What is Java Exception?

 An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Q: When to use Custom Exceptions?

 You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

 

Q: When to use Runtime vs. Checked Exceptions?

 If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

 

Q: When to propagate Exception vs. handle locally?

 It depends on your application requirement. If the application layer where exception is thrown (or propagated from lower layer) can handle the exception and does need to inform upper layer about it, it can have exception handling here. But if the application layer cannot handle (or recover) the exception and upper layer is right place to be informed and handle the exception then better re-throw (or pass) the exception.

 

Few more best practices:

  1. Avoid catching top level exceptions.
  2. Log exceptions just once.
  3. Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. We have two options here: (1) Convert SQLException into another checked exception, if the client code is expected to recover from the exception. (2) Convert SQLException into an unchecked exception, if the client code cannot do anything about it.



Thanks!