Java Database Application Library


Get JDAL (Java Database Application Library) at SourceForge.net. Fast, secure and Free Open Source software downloads

JDAL Spring MVC and DisplayTag Sample

To use JDAL in web enviroment with Spring MVC and DisplayTag write two classes and one JSP page:

Reuse the integration and service layers of the sample library that includes three models (Book, Author and Category) and two of the persistent services (BookService and CategoryService)

Adapter

JDAL Page to PaginationList Adapter. Now this class was added to the new jdal-web module so you really don't need to write it.

/**
 * Adapter from JDAL Page to DisplayTag PaginatedList
 * 
 * @author Jose Luis Martin
 */
@SuppressWarnings("unchecked")
public class PaginatedListAdapter implements PaginatedList {
 
	private Page<?> model;
 
	public PaginatedListAdapter() {
		this(new Page(10));
	}
 
	public PaginatedListAdapter(Page<?> model) {
		this.model = model;
	}
 
	/**
	 * {@inheritDoc}
	 */
	public int getFullListSize() {
		return model.getCount();
	}
 
	/**
	 * {@inheritDoc}
	 */
	public List getList() {
		return model.getData();
	}
 
	/**
	 * {@inheritDoc}
	 */
	public int getObjectsPerPage() {
		return model.getPageSize();
	}
 
	/**
	 * {@inheritDoc}
	 */
	public int getPageNumber() {
		return model.getPage();
	}
 
	/**
	 * {@inheritDoc}
	 */
	public String getSearchId() {
		return null;
	}
 
	/**
	 * {@inheritDoc}
	 */
	public String getSortCriterion() {
		return model.getSortName();
	}
 
	/**
	 * {@inheritDoc}
	 */
	public SortOrderEnum getSortDirection() {
		return model.getOrder() == Page.Order.ASC ? SortOrderEnum.ASCENDING : SortOrderEnum.DESCENDING;
	}
 
	/**
	 * @return the model
	 */
	public Page<?> getModel() {
		return model;
	}
 
	/**
	 * @param model the model to set
	 */
	public void setModel(Page<?> model) {
		this.model = model;
	}
 
	public void setPage(int page) {
		model.setPage(page);
	}
 
	public void setSort(String sort) {
		model.setSortName(sort);
	}
 
	public void setDir(String dir) {
		model.setOrder("asc".equalsIgnoreCase(dir) ? Page.Order.ASC : Page.Order.DESC);
	}
 
}
 

Controller

In BookController, store the filter on the session object using the Spring MVC @SessionAtributtes annotation. Bind the list of categories to request with Spring MVC @ModelAttributes for showing it on the filter form.

Since JDAL Core automatically provides us the queries with order and pagination from the information provided by the object Page , the implementation of the handler for new page requests generated by DisplayTag getPage() is very straightforward and can be reused independently of the model shown in the table. We only need to get the Page from the PaginatedListAdapter and call to the PageableDataSource getPage method.

/**
 * Controller to handle "/book" requests
 * 
 * @author Jose Luis Martin 
 */
@Controller
@SessionAttributes("bookFilter")   // Store filter on Session
@SuppressWarnings("unchecked")
public class BookController  {
 
	/** Persistent service for book categories */
	PersistentService<Category, Long> categoryService;
	/** Persistent Service for Books */
	PersistentService<Book, Long> bookService;
 
	/**
	 * Handle getPage request. Gets the Page from PaginatedListAdapter wrapper
	 * and query service for data.
	 * @param paginatedList the displaytag PaginatedList interface
	 * @param filter filter to apply
	 * @return Model 
	 */
	@RequestMapping()
	public void getPage(@ModelAttribute("paginatedList") PaginatedListAdapter paginatedList, 
				@ModelAttribute("bookFilter") BookFilter filter) {
 
		Page<Book> page = (Page<Book>) paginatedList.getModel();
 
		page.setFilter(filter);
		bookService.getPage(page);
	}
 
	/**
	 * Add the category list to model 
	 * @return List with all categories
	 */
	@ModelAttribute("categoryList")
	public List<Category> getCategories() {
		return categoryService.getAll();
	}
 
	/**
	 * Need to register the CategoryPropertyEditor for mapping ids of 
	 * category select to Category objects in bd.
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Category.class, new CategoryPropertyEditor());
 
	}
 
 
	@ModelAttribute
	public BookFilter getBookFilter() {
		return new BookFilter();
	}
 
	/**
	 * @return the categoryService
	 */
	public PersistentService<Category, Long> getCategoryService() {
		return categoryService;
	}
 
	/**
	 * @param categoryService the categoryService to set
	 */
	public void setCategoryService(PersistentService<Category, Long> categoryService) {
		this.categoryService = categoryService;
	}
 
	/**
	 * @return the bookService
	 */
	public PersistentService<Book, Long> getBookService() {
		return bookService;
	}
 
	/**
	 * @param bookService the bookService to set
	 */
	public void setBookService(PersistentService<Book, Long> bookService) {
		this.bookService = bookService;
	}
 
	/**
	 * Property editor to map selected category from id string to Category.
	 */
	class CategoryPropertyEditor extends PropertyEditorSupport {
 
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			Long id = Long.parseLong(text);
			Category value = id == 0 ? null : categoryService.get(id);
			setValue(value);
		}
 
		/**
		 * {@inheritDoc}
		 */
		@Override
		public String getAsText() {
			Category c = (Category) getValue();
			return c != null ? String.valueOf(c.getId()) : "";
		}
	}
}

View


Finally, write the JSP page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="<c:out value="${pageContext.request.contextPath}"/>/styles/displaytag.css"/>
<title>JDAL Spring MVC and DisplayTag Sample</title>
</head>
<body>
<H1>JDAL Spring MVC and DisplayTag Sample</H1>
 
<form:form commandName="bookFilter" action="getPage" method="POST">
      <table>
          <tr>
              <td>Book Title:</td>
              <td><form:input path="name" /></td>
          </tr>
          <tr>
              <td>Category:</td>
              <td><form:select path="category">
                <form:option value="0">--Please Select</form:option>
                <form:options items="${categoryList}" itemValue="id" itemLabel="name" /><
                </form:select>
              </td>
          </tr>
           <tr>
              <td>ISBN:</td>
              <td><form:input path="isbn" /></td>
          </tr>
           <tr>
              <td>Author Name:</td>
              <td><form:input path="authorName" /></td>
          </tr>
           <tr>
              <td>Author Surname:</td>
              <td><form:input path="authorSurname" /></td>
          </tr>
          <tr>
              <td colspan="2">
                  <input type="submit" value="Apply Filter" />
              </td>
          </tr>
      </table>
  </form:form>
 
  <br>
 
  <display:table name="paginatedList" requestURI="getPage" >
    <display:column property="id" title="ID" sortable="true" style="width:80px" />
    <display:column property="name" title="Title" sortable="true" style="width:300px "/>
    <display:column property="category" title="Category" sortable="true" sortProperty="category.name" style="width:200px"/>
    <display:column property="author" title="Author" sortable="true" sortProperty="author.surname" style="width:200px" />
    <display:column property="isbn" title="ISBN" sortable="true" style="width:180px"/>
</display:table>
 
</body>
</html>

Sample Source Code

Source code is in jdal-samples.tgz file. Download the latest version from sourceforge.

If you have comments, questions or something else, please make a post on project support forums. I will try to answer it as soon as I can.