Monday, July 23, 2012

Placing your custom tags inside a JAR with Maven

I recently wrote an article about packaging a TLD file inside a JAR and how to reference it to enable systematic reuse for these resources.
Other resources that likely you want to reuse are your custom tags.
This is very similar to packaging TLDs function files.
Let's start with a simple tag that substitutes the well-known IE checks for the CSS.
So, instead of writing
<!--[if IE 8]>
<link rel="stylesheet" href="ie.css" type="text/css" />
we'll be able to write
<my:ie test="IE 8" css="ie.css" />

The tag itself is quite easy. It will look like that
<jsp:root xmlns:c=""
 xmlns:jsp="" version="2.0">
 <jsp:output omit-xml-declaration="yes" />

 <jsp:directive.attribute name="check" required="true" />
 <jsp:directive.attribute name="css" required="false"/>
 <jsp:text><![CDATA[<!--[if ${check}]>]]></jsp:text>
 <c:if test="${not empty css}">
  <link rel="stylesheet" href="${css}" type="text/css" />
 <jsp:doBody />


Actually this tag does also something more, but that's out of the scope of this article.
Now all you need to do is to place this tag inside the src/resources/META-INF directory. If you want to be tidy, you can even place it under a subdirectory, "tags" for example.
Now all you need to do is to add a TLD file under the META-INF directory as explained in the aforementioned articles describing your new tag, like that:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="" 
 xsi:schemaLocation="" version="2.0">
Be careful to use the correct value for the URI tag because that's the trick to reference this file from your JSP projects.

Hope you can find this helpful,

Tuesday, July 10, 2012

Simple form validation with Spring MVC

While developing a web application it's always wise to provide users with feedback about form validation rather that present them the error.
Here, I want to show how to accomplich this task within a Spring MVC application.
First, write down the model against which validation will be performed. A model is nothing more than a POJO.

public class FormModel {
 private String name;
 private String surname;
 private Long years = 0L;

        // getters and settes omitted

The model has just two String members and a Long member. Let's suppose that the two strings cannot be empty (means, not null and containing at least one char) and that the Long must be greater than 0.
What we need to do now is to write down a validator for this object. I'm not going to implement the Spring Validator interface here to keep things as simple as possible.

public class FormModelValidator {
 public void validate(FormModel model, BindingResult bindingResult){
  if(model.getName()==null || model.getName().length()==0){
   bindingResult.rejectValue("name", "validation_form_model_name");
  if(model.getSurname()==null || model.getSurname().length()==0){
   bindingResult.rejectValue("surname", "validation_form_model_surname");
   bindingResult.rejectValue("years", "validation_form_model_years");


You can see that in the rejectValue methods I've used a code rather than a phrase: this is to localize your error messages. Now, the controller class. This is the class responsible of the binding between the application logic and what the user sees. As I said before, I want to keep things simpe: this is not the formal definition af a controller, you can find it here on Wikipedia.

public class FormController {

 private FormModel model = null;

 public FormModel injectModel() {
  if (model == null)
   model = new FormModel();
  return model;

 @RequestMapping(method = RequestMethod.GET)
 public String index() {
  return "index";

 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView doPost(@ModelAttribute("model") FormModel model,
   BindingResult bindingResult) {
  FormModelValidator validator = new FormModelValidator();
  validator.validate(model, bindingResult);

  if (bindingResult.hasErrors())
   return new ModelAndView("index");

  ModelAndView mav = new ModelAndView("index");
  mav.addObject("model", model);
  mav.addObject("message", "VALUES SUCCESSFULLY VALIDATED");
  return mav;

You can even skip the implementation class and move al the code in the controller class.
Let's take a look at the controller.
We can see that it responds on the root path. It injects in the model our object (what we need to validate). It also handles the POST of the form (this is where the validation is performed).
You can also notice that our FormModel object is stored as a member of the controller class. This allows persistence between different posts of the form.
The last thing we need to take a look at, is the form.

<form:form method="post" modelAttribute="model">
 <div class="rows">
  <div class="row">
   <form:input path="name" />
   <form:errors path="name" cssClass="errors" />
  <div class="row">
   <form:input path="surname" />
   <form:errors path="surname" cssClass="errors" />
  <div class="row">
   <form:input path="years" />
   <form:errors path="years" cssClass="errors" />
 <div class="submit">
  <input type="submit" value="VALIDATE" />

As you can see it is very simple. Just don't forget to include the namespace
in your page directives.

You can check out the code (as a Spring Roo project) at this repository.


Friday, July 6, 2012

Spring and JSON requests

In modern web applications it's almost vital to enable asynchronous page load protocols, such as AJAX.
This pattern is usually implemented with a client library (such as jQuery) that performs asynch calls to your web application and implementing controllers that handles this request returning JSON data.
To show this I'm going to suppose to load asynchronously the employes based on the office ID they work in.
First, the client side. Using jQuery it is very simple:
function loadEmployesByOffice(officeId){
  type : "GET",
  url : employes_service_uri_byofficeid,
  data : {
   "officeId" : officeId
  dataType : "json",
  success : function(employes) {
   // some code to show the employes
  error: function(){
where the var employes_service_uri_byofficeid is a valid uri pointing to your web application.
Next step is implementing the controller. Be careful: it must respond on the same path as the url parameter in the $.ajax call. I'm assuming something like
@RequestMapping(value = "/services/json/employes")
class EmployeeService{

 @RequestMapping(value="/byofficeid", method=RequestMethod.GET, produces="application/json; charset=utf-8")
 @ResponseBody public String loadEmployesByOfficeId(@RequestParam("officeId") Long officeId){
  Collection employes = .... // load the employes
  return (new Gson()).toJson(employes);

Here I'm assuming to use Gson as JSON marshaller. That is not the only choice: you could use Jackson or, if you are using Spring Roo, just add JSON support to your entities by adding the @RooJson annotation to your entity.
Note that the name "officeId" is the same in the jQuery call and in the @RequestParam annotation. This  can be omitted if the formal parameter in controller method has the same name.
Also, note the
produces="application/json; charset=utf-8"
this is important for IE that otherwise could fail while parsing the response.

You can check out a sample application built with Spring Roo 1.2.1. at this url.
That's all.


Wednesday, July 4, 2012

Use a TLD placed in a JAR in JSPX

If a TLD is placed inside a JAR as explained in this article then using it from inside a JSPX file is very easy.
You just need to specify it in the root node of the JSPX file. For example
<div xmlns:your_namespace="URI"
where URI is the value of the URI tag in the TLD. Referring to the tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="" 
 xsi:schemaLocation="" version="2.0">

URI is


Packaging your TLDs with Maven

Packing your TLDs files with Maven can be very useful to allow systematic reuse of these resources. It is also fairly easy to accomplish.
First add the Maven resource plugin to your build. In pom.xml, locate (or create) the build/plugins section and add the following


No configuration needed if you respect the conventions shown below.
Resource files in Maven are by default located in folder src/main/resources. Include it in your build path if it isn't yet (if necessary, create it) as a resource folder.
Create the subdirectory META-INF under the src/main/resources and place your tld file here. Don't forget to specify the uri node, as follows

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="" 
 xsi:schemaLocation="" version="2.0">


That's it! Now your TLD will be placed in your JAR.
Also using it is very simple. Just follow this link.