Sitemesh 2 with Spring MVC 3 – multiple layout for multiple controller

Recently I had bitter experience setting up different layout in sitemesh for different controller of Spring. In general as a developer my expectation is for different controller I setup different url and for each url I add a decorator with unique name and different layout page.

For instance, I have two controllers – AdminController and UserController as follows.

@Controller
@RequestMapping("/admin")
public class AdminController {

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "admin/index";
    }
}
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "user/index";
    }
}

So, url project/admin/index – points to admin controller’s index page
and url project/user/index points to user controller’s index page.

Now I want to decorate two urls with two different sitemesh layout. decorator.xml looks like –

<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/WEB-INF/layouts">
    <decorator name="admin" page="admin.jsp">
        <pattern>*admin*</pattern>
    </decorator>

    <decorator name="user" page="user.jsp">
        <pattern>*user*</pattern>
    </decorator>
</decorators>

However, it wasn’t behaving as I expected. I wasted a lot of time trying different combination in pattern like /projects/admin*, */admin/* etc.
Continue reading

Double Brace Initialization in Java

It is a subtle use of two basic java conceptions. First, we can create an anonymous inner class in time of class instantiation, syntax for which is usual

new Person(){};

Remember we are not exactly creating an object of Person rather we are creating an object of anonyms subclass.

Then we can define any number of initializer block in a class [Official Doc]. Syntax for that is

class Person {
    {
        System.out.println("In an initializer block");
    }
}

Bingo! Lets combine them both we get the double brace initialization

new Person(){{
    //do anything with this subclass of person
}};

Continue reading