Saturday, April 13, 2013

Spring Tiles Integration

Suppose if your web page has a standard header, footer and only center content will be changed, it is very difficult to hardcode in each and every webpage and if later if any changes is needed then all pages needs to be updated with the relevant details. Here comes Tiles which helps you to templatize the common items and include it in each and every page.

Lets see how we are going to integrate the Titles in our Spring MVC. Our application layout will have the standard header and footer across all web pages, where only the center content will be changed.

Make sure that you have the following jars files included in your lib


Configuring titles framework in Spring MVC



Using the definitions attribute, we need to specify the tiles definition file. The tiles-def.xml definitions are below, the file should be located under WEB-INF directory in your application. In the tiles-def.xml we need to define our base layout structure. The base layout we are building contatins the attributes title, header, body and footer. We need to create the baseLayout.jsp and place it under /WEB-INF/titles, the template baseLayout.jsp, will contain the different segments of a web page, header, body and footer.


BaseLayout.jsp - View Template
<%@ taglib uri="" prefix="tiles"%>
<tiles:insertAttribute name="title" ignore="true"/>


To display the views, we use the ResourceBundleViewResolver. By default the will be used to store
the key value pairs



Controller File
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("dealerList" , dealerList);		
return new ModelAndView("dealerlist", modelMap);

The base, delear in refers to the definition name in the tiles-def.xml file. The hello and dealerlist refers to the modelview name sent by your controller.

That's all you have integrated the Tiles with Spring MVC

Happy Programming...!!!

Thursday, April 4, 2013

Spring MVC - Bind an input field to a Date property

For request parameters representing string, number, and boolean values, the Spring MVC container can bind them to typed properties out of the box. Suppose you have the Date Input field, and the bean property is defined as Date Type, when container tries to bind it will throw exception

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

So we need to create a binding between your input field and your bean's Date property. Spring provides a PropertyEditor named CustomDateEditor which you can configure to convert an String to respective date format. You typically have to register it in a @InitBinder method of your controller

public void initBinder(WebDataBinder binder)
    //binder.registerCustomEditor(ExpenseType.class, new ExpenseTypePropertyEditor());
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

Happy Programming..!!!