jQuery Simple Forms

GitHub repo: https://github.com/pgrimard/simple-forms

I just published a set of handy jQuery plugins for working with forms!

It includes the following:

  • Function to serialize a form to JSON.
    This is useful if you’re submitting a form via AJAX and need to serialize your form to JSON.  The form serialization will also look for data-default-value attributes on your named form elements and use that value if the input is left blank.  The default value is also verified to see if it’s numeric, in which case the resulting JSON property will be numeric.
  • Function to add new option to an HTML select.
    Adds a button next to your select that when clicked, replaces your select with a text input of the same name, ID and classes.
  • Enable/Disable buttons.
    Simple functions for enabling/disabling buttons.

Spring Security CSRF Protection in a Backbone single page app

Be advised this post has been revised since it’s original writing.  Rob Winch, Spring Security project lead suggested a simpler method of doing what I needed and indeed, it is simpler.

Happy New Year!!  What better way to kick off this new year than to write a new post?  Let’s get to it.  This post will not try to show you best practices for protecting against CSRF (cross-site request forgery).  Instead, I hope to start a discussion on what would be the best way to achieve CSRF protection in a Backbone app using the new Spring Security 3.2.0 release, so that I may better understand it myself.  The source code for this experiment is available at the bottom of this post.

What does Spring Security CSRF protection assume?

In version 3.2.0, CSRF is enabled by default when using Spring Security.  Since I’m building a Backbone app which will be accessed from a browser, I want the added protection.  While reading the documentation, I quickly realized that the way the implementation has been done, the CSRF token needed on your page is stored in a session attribute on the HttpSession.  On the backend, the CSRF token is created using a HttpSessionCsrfTokenRepository.

The token is created automatically when you request the page being protected.  This doesn’t pose any problems if you’re building your app with JSP for example.  If you’re using Spring MVC’s JSP tag libs, or something like Thymeleaf (which I loved using before discovering Backbone) then the CSRF token is available for you as a page attribute when the page is rendered on the server and can be inserted in a form for example or in a meta tag for later use in an AJAX request.  In a Backbone app however, where the  page is rendered primarily in the browser, you need another means to get that CSRF token when you first load the page because we don’t get access to page attributes like we do in JSP.

How about a servlet filter?

One thought I had to retrieve the CSRF token at page load was to create a servlet filter.  This allows me to retrieve the CSRF token from the request and add information about it as response headers.


Cross-Origin Resource Sharing (CORS) requests with Spring MVC

Welcome back!  :)  This will be a brief post to show you how to setup CORS in your Spring MVC application.  The objective here is to keep the code out of my @RequestMapping request handlers so that it can be easily used across the application.

The CORS Filter

The first thing we need is a CORS filter.  When you make an AJAX request from your domain to another domain, the first thing that will happen is an OPTIONS request will be made to the URI in question to determine what requirements are needed to complete this request.  This request is where we need to verify that the origin is actually allowed to make that request and send back a response to the browser permitting it to proceed.  We will retrieve the “Origin” header from the servlet request and verify that it’s one of the origins permitted to to make CORS requests to the application.  Assuming the origin is permitted, we’ll add a “Access-Control-Allow-Origin” header to the servlet response which will contain the value of the incoming “Origin” header.  Let’s extend Spring’s OncePerRequestFilter, verify the origin, then adjust the response headers.


Yeoman Backbone apps meet Tuckey’s UrlRewriteFilter!

A couple months ago, I started using Yeoman to rapidly scaffold out webapps with AngularJS.  I even wrote a quick blog post about Yeoman, as well as how to use the Yeoman Maven plugin when writing webapps in Spring and setting up the Jetty Maven plugin to use the scaffolded app during development.  Since then, I’ve begun using Backbone and Underscore and I’ve honed how I use Yeoman on a daily basis.

Today I don’t really use the Yeoman Maven plugin anymore during development.  Indeed it is a great plugin.  The main issue I had during development time was the time it took to complete a build because the Yeoman Maven plugin is doing a few long lasting IO tasks over the internet.  Combine with that the fact that I didn’t need to actually build my entire WAR every time I wanted to compile changes I made to my JavaScript source.  In fact, for the most part, the servlet part of my webapp didn’t require much changes at all since I was mainly exposing REST endpoints producing JSON data.  Now during development, I simply build my WAR once (assuming there are indeed no changes to make on the server side) and test my app using the Jetty Maven plugin as usual.

A few things have changed in my application structure in the past couple months.  When I started using Yeoman, I was creating a directory called “yo” outside of my usual src/main directory structure used by Maven.  At the time, it seemed like the right thing to do from what I was reading in blog posts and StackOverflow.  Over the course of development, this posed a few challenges that I spent some time trying to find solutions to, but nothing seemed all that elegant or straightforward.  So the first big change to my structure is now I run my Yeoman commands within my src/main/webapp directory which Maven does recognize by default.


Jetty and the Yeoman Maven Plugin

Everyone knows productivity is important. For me, anything that can be automated in my development lifecycle is a major win for me. Recently, I’ve been focusing a lot of my development energy on JavaScript and client side development. One particular framework I’m really interested in is AngularJS. I won’t go into details about it in this post, that’s not my goal of this post.

As I started exploring AngularJS, I came across Yeoman which is a tool for rapidly scaffolding out an application. I played with it for a while and was instantly hooked by the evident productivity gains I could achieve. With the aid of a few other tools, Yeoman creates a nice workflow for writing web apps that perform well. You get minified CSS and JavaScript for your app, so the server requests are fewer and quicker. This is achieved with Grunt which is the build tool for your app. Another tool called Bower takes care of third party package management, similar to Maven in the Java world.

All that productivity is great, but I want more. I found the yeoman-maven-plugin. This plugin has proven very useful in my development. Essentially, instead of running the grunt command from the command line, this plugin does that for you during your Maven build while ensuring bower gets all the needed dependencies. With a little configuration, this plugin becomes an integral part of building a webapp with Maven and utilizing Yeoman without much additional effort.

Setting up The Jetty Maven plugin

Now that we’ve got the Yeoman Maven plugin setup, lets look at setting up the Jetty Maven plugin to work with our new directory structure. I really like using Jetty in development because its quick. The problem I ran into though is that simply using “jetty:run” doesn’t work with our Yeomanified app. Jetty doesn’t know about the yo/dist directory created by Yeoman. This is actually pretty easy to accomplish once I figured it out. Here’s the plugin config in my pom.xml.

                    <baseResource implementation="org.eclipse.jetty.util.resource.ResourceCollection">

With the above Jetty Maven plugin config, now running “jetty:run” will tell Jetty to also look in yo/dist for web resources.


Please visit the Yeoman Maven plugin page on Github for setup instructions.

If you can read French, the plugin’s author Thomas posted a great post to.

While developing from IntelliJ on my Mac, I had the issue of npm, yeoman, grunt and bower not being found by Maven. The Yeoman plugin’s author pointed out that these tools weren’t on my PATH variable. Once fixed, the tools worked fine when Maven ran inside IntelliJ. You can refer to my Stackoverflow post for the answer from Thomas ;)

Implementing your own Spring Security authentication provider is easy with Spring Roo and Spring Data JPA

If you’re using Spring Roo and Spring Data JPA, then implementing your own Spring Security authentication provider in a Spring MVC application is pretty simple to do.

The first thing you need is an entity class that represents the user table in your database.  That’s the table where usernames and passwords reside.  Creating an entity with Roo is easy.  The first thing you have to do after you’ve created your entity is update it to implement Spring Security’s UserDetails interface.  Your resulting entity should look something like this.  This example is very basic.

@RooJpaEntity(table = "USERS", versionField = "")
public class Person implements UserDetails {

    private String username;

    private String password;

    public Collection<? extends GrantedAuthority> getAuthorities() {
        // your logic goes here

    public boolean isAccountNonExpired() {
        // your logic goes here

    public boolean isAccountNonLocked() {
        // your logic goes here

    public boolean isCredentialsNonExpired() {
        // your logic goes here

    public boolean isEnabled() {
        // your logic goes here

As you can see, there’s not much to it.  Since we’re using Roo, the getters/setters for username and password are created for us.  The UserDetails interface requires us to have a getUsername() and getPassword() method, but since our private fields are called username and password, the required getters are generated by Roo.

Next we need a Person repository.  Creating this repository using Spring Roo is also very easy.  Using Spring Data JPA, the resulting repository interface looks like the following:

@RooJpaRepository(domainType = Person.class)
public interface PersonRepository {

Not much to it indeed.  Underneath the covers, the Roo generated ITD takes care of annotating our repository with @Repository and extending Spring Data JPA’s JpaRepository and JpaSpecificationExecutor interfaces.

Now that we have our UserDetails implementation and our Spring Data JPA repository, we need to implement Spring Security’s UserDetailsService interface.  This interface is quite simple in that you only need to implement one method called “loadUserByUsername”.  Simply injecting our newly created PersonRepository, we can very easily return the Person record we find using the username passed to “loadUserByUsername”.  Our repository returns Person instances, but the “loadUserByUsername” method returns an instance of UserDetails.  If you remember, our Person entity implements UserDetails, therefore returning a Person instance from the PersonRepository satisfies our UserDetailsService implementaiton.

public class MyUserDetailsService implements UserDetailsService {

    private PersonRepository personRepository;

    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {

        return personRepository.findOne(username);

Finally, all we have to do is update the Roo generated applicationContext-security.xml configuration file to use our custom UserDetailsService.

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="myUserDetailService"/>

That’s basically all there is to it.  In your application, you’ll have your own logic for loading the user’s granted authorities in the Person entity, so I didn’t go into any details there.

Tutorial: Unmarshalling SOAP Maps with JAXB into a List of Objects with a sprinkle of Spring Integration

Back in August, I posted about invoking web services with Spring Integration using XStream marshalling/unmarshalling.  That post was based on a project I had just finished at the time.  Recently, I had to make some changes to that project in order to implement another web service offered by the same provider.  This particular web service was returning a SOAP Map like before, however instead of a simple String key and String value, I had String keys and Map values.  With XStream, this seemed to be not so simple to implement.  After a bit of looking around, I decided to try and swap out XStream for JAXB.  I could have simply added JAXB and used it strictly on the new web service, but it sounded like more fun getting JAXB working across the application with a more sophisticated implementation than what I had done with XStream.  The other thing I wanted to do was unmarshal the Map as a List of Objects because for the most part, the key itself didn’t matter too much and there was a finite list of those keys.  Here’s a sample excerpt of XML being returned by the new web service.

    <key xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">mainkey</key>
    <value xsi:type="ns1:Map">
            <key xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">key1</key>
            <value xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">value1</value>
            <key xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">key2</key>
            <value xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:string">value2</value>

Register your classes with the JAXB marshaller

In Spring, there’s the convenient OXM namespace for registering various types of XML marshallers.  Here’s how we register the JAXB annotated classes with the JAXB marshaller.

<oxm:jaxb2-marshaller id="jaxbMarshaller">
    <oxm:class-to-be-bound name="com.patrickgrimard.ws.Request"/>
    <oxm:class-to-be-bound name="com.patrickgrimard.ws.StringResponse"/>
    <oxm:class-to-be-bound name="com.patrickgrimard.ws.MapResponse"/>
    <oxm:class-to-be-bound name="com.patrickgrimard.util.StringDataItem"/>
    <oxm:class-to-be-bound name="com.patrickgrimard.util.ArrayDataItem"/>

The first thing I did was start writing an API for dealing with Maps that had String values, and then adapted it to handle Map values.

Unmarshalling simple Maps of String values into a List of Objects

This starts with a simple interface I created using Java Generics called DataItem<T>.  Now if anybody’s used JAXB, they know that when unmarshalling XML with JAXB, it can’t handle interfaces, so the objects and their properties need to be concrete implementations that can be instantiated.  Here is the DataItem<T> interface.

public interface DataItem<T> {
    public String getKey();

    public void setKey(String key);

    public T getValue();

    public void setValue(T value);

With this interface, we can specify the type of the Map’s value property.  The first implementation of this interface will be StringDataItem. (more…)