Integrating Spring MVC with Hibernate Annotation-Based Validation

In this article, I would like to demonstrate how to integrate Spring MVC, Spring bean validation framework and hibernate validator using annotations. The Hibernate Validator project is implementation of JSR 303 – Bean Validation standard, which defines a metadata model and API for JavaBean validation. For the the purpose of this example, I used Spring Framework v3.0.5 and Hibernate Validator v4.1.0.

What I like about Spring + Hibernate validation, is that this combination eliminates the need to use validator classes in controllers for bean validation. In other words, less code, less classes, everything looks much cleaner.

I am not going to talk about how to build web application from scratch using Spring MVC. I assume that you already have something working in place. I am just going to show the important bits needed, in order to plug hibernate validation in to your code:

1. Define two following beans in your application context XML in your WEB-INF directory:

<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. A JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.

<bean id="messageSource"
     class="org.springframework.context.support.ResourceBundleMessageSource">
	<property name="basename" value="/WEB-INF/message-resources.bundle" />
</bean>

The bean above knows how to access resource bundles using specified basenames.

2. Create resource bundle (in this example it is “message-resources.bundle”) under WEB-INF. The resource bundle is where you should define your validation messages that the end user sees if his form submission fails validation. Please note that the bundle does not have to be at the root of WEB-INF, it can be placed also in a sub-directory of WEB-INF. The format for validation messages in your bundle should be as follows:

Annotation.bean-variable-name.bean-propery=validation error message.

For example:

NotBlank.someFormName.name=Name must not be blank,
Size.someFormName.name=Name must be less than or equal to {1} characters.
NotBlank.someFormName.street=Street name should not be blank. Please enter a value
NotEmpty.someFormName.selectedItem=Item selection is required

The example above describes four different validation messages for different validation rules. In case of a particular validation rule disobeyed, its respective validation message will be found based on the validation annotation, bean name and bean property name.

3. In your controller, in the method that validates bean from the POST request, annotate your bean with annotation @Valid. For example:

@RequestMapping(value = "/update.html", method = RequestMethod.POST)
 public String update (    @ModelAttribute("someFormName")
 @Valid SomeForm someFormName,
 BindingResult result,
 Model model)
 {

 if(result.hasErrors()) {
 // Return view name
 }

 // Do stuff

 // Return view name
 }

The @Valid annotation is part of the standard JSR 303 – Bean Validation API, and is not a Spring-specific construct. The Hibernate Validator instance invoked when a @Valid method argument is encountered.

Very important: your bean variable name in your controller method (in this case its “someFormName“) must match the bean variable name in your validation message resource bundle.

4. Annotate your bean member variables with annotations that tell Hibernate Validator what should be validated and what are the validation rules:

public final class SomeForm {

 @NotBlank
 @Size(min=0,max=20)
 private String name;

 @NotBlank
 private String street;

 @NotEmpty
 private String selectedItem;

 // Getters

 // Setters
}

As you can see from the above bean, the three fields that should be validated are annotated with @NotBlank, @NotEmpty and @Size. The validation rules are simple: the name property must not be blank nor longer than 20 characters, street property must not be blank, while selectedItem must not be empty.

By the way, you can have more complicated validation rules in place using annotations. It is possible to use expressions which decide whether validation rules should fire. Consider the following, which validate an email field:

@Email(applyIf="email is not blank")
@NotBlank
private String email;

You don’t want to display invalid email format error message when the filed is blank. Therefore that above expression in @Email annotation will have the rule fired only when the property is not blank. Expression can be especially very convenient when validating password fields:

@NotBlank
private String password;

@NotBlank(applyIf = "password is not blank")
@Expression(value = "confirmedPassword= password", applyIf = "password is not blank")
private String confirmedPassword;

Validation rules for confirmedPassword property will fire only when password field will not be blank.

That’s it :) If any rule(s) are disobeyed, the BindingResult result object will be populated with appropriate error messages, loaded from your message bundle. The error messages then can be displayed in your JSP using Spring tag:

<spring:hasBindErrors name="someFormName">
	<c:forEach items="${errors.allErrors}" var="error">
		<spring:message message="${error}"/>
	</c:forEach>
</spring:hasBindErrors>

And that is it! Feel free to post a comment if you run into problems and I iwll try to help you the best I can :)

Cheat Sheet for Selecting Map/List/Set in Java

I have prepared a cheat sheet that can help to select appropriate Map, Set or List implementation when required. Java API has many implementations of interfaces mentioned, and it is not always clear which implementation should be used in a particular scenario. The cheat sheet comes in the form of a flow chart, which makes it easy to follow and understand.

The idea was inspired by Sergiy Kovalchuk. Sergiy made a flow chart using the most commonly used collections. I tried to take it one step further and make it much more thorough.  Please do let me know if anything needs to be corrected. I hope this can help developers out there to choose the right collection for the right job.

Cheat sheet for selecting appropriate set/list/map in Java

Click on the image to load it in a new window

Inspired by Sergiy Kovalchuk

The Truth About “SEO In a Box” Or Gimmicks Alike

In this article I would like to speak about SEO (Search Engine Optimization) services offered by some companies and/or individuals on the Internet.  I am not an SEO expert, but I do have some clue what it means. The reason for me writing about this is a discussion that I had with one of my friends over a beer. My friend (lets call him Mark) has an online business, that sells some gadgets and obviously as any other online business owner, wants to be ranked higher in search results and get more traffic to his site.

During the chat, Mark started telling me with excitement how he came across some SEO product online, product that promises people fast results in terms of ranking. The vendor of the product (SEO in a box, package, suitcase or some other type of container) swears that once you commit and purchase it, you will know for sure the secrets of how to obtain first position in Google search results and overall SEO secrets in general.

Now, Mark is a good business man, but he is not really a tech savvy guy. So after patiently listening to his fascinating story, I asked him: “Do you know that SEO cannot be packaged in a box, nor it comes as a software, and it is actually a process?”. As an answer, the only thing I got back was an empty stare: “What do you mean?”. I saw that I need to spend some time on that, so I quickly finished my beer, and replied:

Imagine that SEO is like a diet. You cant do it in one go, one day, one hour – you can try, but you wont get any results. It is a process, you have to change your life style, what you eat, what you do etc., and after a period of time you are going to get results. SEO works in a similar way – you need to undertake a number of steps to ensure that your SEO yields results. For example, the following are some of the common things you can have in place:

  1. Make sure that your HTML code validates using W3C HTML Validation Service. In terms of application, its easier for search bots to index your pages.
  2. To have a domain name which describes the nature of your business is a big plus too
  3. No broken links. You get really penalized for that.
  4. Good quality content, frequent site updates
  5. Link building with other sites/blog (I am not talking about link farming, but genuine replies on other blogs/site to try to engage users to visit your site)
  6. Keyword optimization
  7. Submission of your site/blog to quality blog and website directories
  8. To leverage social media like Facebook or/and Twitter (Not an SEO technique, but just another way to try to increase traffic to your site)

To do what I mentioned previously can take some time, and still it does not guarantee that your website is going to be ranked 1st. Think what about other businesses like your self that are doing SEO for their websites? It is a tough competition.

Some of the companies that sell these products are often making use of black hat SEO techniques in order to deliver fast results to their customers.

What is black hat SEO? Black SEO techniques help to manipulate relevance of search results within a short period of time. Some dudes that do SEO full time can be really good at it. They learn from observation after many trial-and-errors how search engines react in certain situations.

It is a known fact these days, that the more links point to your site – the higher your page rank is with Google, and the better it is for your search results. Therefore some websites willingly exchange links with you. Some other websites that have high traffic of visitors, wont exchange links with you, but will link to you for a fee. This is called link farming, one of the black hat SEO techniques.

Google does not like manipulations. It is smart enough to identify websites that do black hat SEO. Therefore when such website detected, it is going to be buried deep deep inside the pages of search results. Long story short – shortcuts do not work, or if they do work, you as a web site owner should be prepared to bare possible consequences in the future. If you are running a successful business, last thing that you need is to be penalized by search engines for your short cuts.

I am not saying that the moment you exchanged a couple of links you are doomed. There are many blog/sites out there who exchange links with friends. Its just looks suspicious when you start hosting hundreds or even thousands of links to other sites, or let someone who does link farming link to your site. Google is able to pick up on many naughty things some people do in order to spin off their sites.

Therefore the whole idea of “SEO in a what not” is ridiculous. Many of these SEO software companies target people who do not really understand what SEO is really is. These guys try to sell an illusion that the moment you paid for their course, software or what not, you are going to be promised a spot on the first page.

No one can really tell you the secrets of how Google operates (unless its actually a Google engineer directly involved with search algorithm or Sergey Brin himself), its all one big illusion, sold to non-tech business people in order to scam some quick cash. Well this is just my opinion about the whole thing ;-)

Update

A buddy of mine who is tinkering with SEO techniques made some comments:

- Validation in W3C is really not needed… It’s good practice I agree, but really what should be said is that the developer should be using a clean, css-based layout with scripts (css, js etc) being stored externally.

- Domain name describing the business is less important that having a domain name that contains the keyword(s) you are wanting to get ranked for. Also, having a .com.au for an Aussie businesses is generally better than having a .com

- On broken links… Yes this is true, but worth elaborating, tell the user to setup Webmaster Tools & check for 404s. If they exist, 301 redirect to the most appropriate page.

- Directories are almost pointless in this day & age. I’d pick the top 3 in your location / relevance area & move on. (for example, hot frog is a good one for aussies)

- Leveraging social media is actually becoming an SEO technique now, Google assigns value to the popularity of your content of social networks, its only a fairly recent phenomena. It’s also VERY useful for getting pages indexed. (tweet the full URL and you’ll have google bots there in a jiffy ;) )

How To Define a Spring Bean With Generics Parameter

At the time when this article was written, the Spring framework does not allow to define beans in application context xml file using parameterized classes. The reason for that is that generics parameters are compiler information, and not run-time. Compiler information is something that Spring does not care about. For example, the following (or something similar) will NOT work:

<bean id="someClass" class="asia.javabeans.SomeClass<asia.javabeans.Blah>"  />

Sometimes, this restriction can create a problem if you have a parameterized class that has to be loaded by Spring. As a workaround, create an empty child class that extends your parameterized class, and then use that class’s canonical name as your bean definition. Consider the following parameterized parent and the extending child classes:

public class SomeParent<Blah> {

}

public class Child extends SomeParent<Blah> {
   // Just an empty class
}

and your Spring definition can now look like this:

<bean id="childClass" class="asia.javabeans.Child" />

The down side here is that you get stuck with an empty class, but at least you can have your bean definition in your application context xml file.

Inheritance and Generics with Abstract Data Types

In this article, I want to demonstrate a simple inheritance example that uses generics.  The abstract parent class is generic in the type, and it defines an abstract method that accepts as a method parameter the generic data type.

The generic data type used by the extending child in the implementation of the abstract method. This example is going to discuss the benefit of this approach.

Consider the following parent class:

public abstract class Parent<T> {
    protected abstract void process(T data);
}

Consider the following two child classes that extend the parent:

public class Child extends Parent<SomeClass> {
    @Override
    public void process(SomeClass data) {
        // Do stuff
    }
}
public class AnotherChild extends Parent<OtherClass> {
    @Override
    public void process(OtherClass data) {
        // Do stuff
    }
}

You can clearly see how this approach creates flexibility when multiple child classes require different data type parameters when implementing the abstract method. Because of the generic type setting in the abstract method, any data type can be passed to the child. This approach can be particularly useful when implementing a strategy design pattern.

CrowdSauce is Live!

This is one of the coolest ideas that I have seen since Facebook became a hit. CrowdSauce is a new location based application that allows you to harness the power of the people to get discounts from businesses. CrowdSauce was born out of the idea that, the people, have the power to put pressure on businesses by using the power of the crowd. What is most important – its really fun :)

You get medals as you make requests for rewards from businesses, and you get promoted in rank. They have this army system going on. I am a second lieutenant now :))