Archive for the ‘Spring’ Category

How to configure validation in Spring MVC controllers

30/05/2014 Leave a comment

Validation is the action through which the application checks that data respects logical (e.g. empty fields, invalid formatted values) and business (e.g. min/max values) constraints.

In order to configure validation for you model objects in Spring, you can follow these steps:

  1. Import the appropriate validation specification and validation implementation jars
  2. Define a class which implements the org.springframework.validation.Validator interface
  3. In the controller method signature, you must annotate the model attribute you’re trying to validate with @Valid (javax.validation.Valid)
  4. In the controller method, you must check whether errors have been identified
  5. If errors are found, reload the page and display the error messages.

In order to have an example on how this works, I’ve written a small test project, using Maven. I am using a jsp page which contains spring:form tags and an in-memory list of users, in order to simulate data access.

Read more…


How to configure Spring Security using annotations

24/04/2014 Leave a comment

As far as integrating Spring Security into a Spring enabled project, there are 2 possibilities, both presented in detail on-line, in the reference documentation:

1. using Java Configuration, see details here This is very useful for applications using the Servlet 3.0 specification, which already register all their servlets by using annotations and which don’t have a web.xml.

2. using XML Configuration, see details here This approach is very useful for applications using specification preceeding Servlet 3.0 or simply for those who use the web.xml for configuration.

My use case is a combination of the both. I have created a web application using Spring and Spring MVC. I have configured my DispatcherServlet in the application’s web.xml. I wanted to use only Java configuration, so I’ve been using an AnnotationConfigWebApplicationContext. When I tried to add Spring Security, I wanted to keep the same approach: Spring Security filterregistered in the web.xml, while all the configuration code would be written in Java. The problem was that the reference documentation doesn’t show how to build such a project (or maybe I missed it). Googleing for a how-to also didn’t return any satisfactory results.

Read more…