Monday, November 26, 2012

JPA 2.0 and Spring - persistence.xml not validated

Yesterday, while running a simple application that required JPA 2.0 and Spring framework, I hit a strange error.
Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'. junit
The solution is actually very simple one you understand the cause.
The problem is releted to the dependencies: the project held a denpendency to spring-jpa-2.0.8 which implements the JPA 1 specification.

So, to solve, I simply changed the dependency to spring-data-jpa-1.1.0.RELEASE.

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" />
<![endif]-->
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="http://java.sun.com/jsp/jstl/core"
 xmlns:fn="http://java.sun.com/jsp/jstl/functions"
 xmlns:jsp="http://java.sun.com/JSP/Page" 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" />
 </c:if>
 <jsp:doBody />
 <jsp:text><![CDATA[<![endif]-->]]></jsp:text>

</jsp:root>

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="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2eeweb-jsptaglibrary_2_0.xsd" version="2.0">
 <tlib-version>1.0</tlib-version>
 <uri>http://mynamespace.org/tags/</uri>
 
 <tag-file>
  <name>ie</name>
  <path>/META-INF/tags/ie.tagx</path>
 </tag-file>
 
</taglib>
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,
Stefano

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");
  }
  
  if(model.getYears()<=0){
   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;

 @ModelAttribute("model")
 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">
   <label>NAME</label>
   <form:input path="name" />
   <form:errors path="name" cssClass="errors" />
  </div>
  <div class="row">
   <label>SURNAME</label>
   <form:input path="surname" />
   <form:errors path="surname" cssClass="errors" />
  </div>
  <div class="row">
   <label>YEARS</label>
   <form:input path="years" />
   <form:errors path="years" cssClass="errors" />
  </div>
 </div>
 <div class="submit">
  <input type="submit" value="VALIDATE" />
 </div>
</form:form>

As you can see it is very simple. Just don't forget to include the namespace
http://www.springframework.org/tags/form
in your page directives.

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

Bye,
Stefano

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){
 $.ajax({
  type : "GET",
  url : employes_service_uri_byofficeid,
  data : {
   "officeId" : officeId
  },
  dataType : "json",
  success : function(employes) {
   // some code to show the employes
  },
  error: function(){
   alert("Error");
  }
 });
}
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
http://domain.com/services/json/employes
@Controller
@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.

Bye,
Stefano

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"
 version="2.0">
 ....
</div>
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="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2eeweb-jsptaglibrary_2_0.xsd" version="2.0">
 <tlib-version>1.0</tlib-version>
 <uri>http://tempuri.org</uri>

 <function>
 ....
 </function>
</taglib>
URI is http://tempuri.org

Bye,
Stefano

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

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.5</version>
</plugin>

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="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2eeweb-jsptaglibrary_2_0.xsd" version="2.0">
 <tlib-version>1.0</tlib-version>
 <uri>http://core.jcz.org</uri>

 <function>
 ....
 </function>
</taglib>

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