Reusable MVC with Htmleasy, resteasy and jsp

In previous post we create set up for multi-modular java project using gradle. Now we are going to explore the sample code behind ugly-web project and what is concept behind the sample in order some of you to use in your own project. Also in previous post we discuss why we are using Htmleasy, resteasy and jsp for our MVC instead of spring MVC. Last thing about ugly-web project is the configuration which can be found on my svn repo. Maybe in the future I will write post about configuration of Htmleasy, resteasy and jsp.

Now let’s start discussion about the sample code. I have code two projects in Spring MVC and I have notice a repeatable copy-paste pattern for handling GET and POST requests, which can be express with algorithms.

GET request algorithm:

step 1. Create new Model
step 2. Return corresponding view for the GET request, with the newly model

POST request algorithm:

step 1. Validate the model, which is created from http request
step 1.1. If model is not valid, return list of errors to the corresponding view
step 1.2 If model is valid, do business logic for successful post handling

I don’t say that your logic in GET and POST methods is similar, but in 80-90% of the time, your business logic can be express with these two algorithms and also implementation of these two simple algorithms is dependent from the frameworks you are using, but in the end you will have reusable behavior for GET and POST.

Our implementation is based on MVC and Template method pattern.

First our GenericModel class, which represents base class for all our Models

import java.util.ArrayList;
import java.util.List;

import org.ugly.interfaces.DomainEntity;
import org.ugly.service.facade.EJBServiceFacade;

import com.googlecode.htmleasy.playground.domain.ValidateResponse;

public abstract class GenericModel {

	protected List<String> errors;
	protected Object[] domainEntities;
	protected EJBServiceFacade bizz;

	protected GenericModel(EJBServiceFacade b, int numberOfEntities) {
		errors = new ArrayList<String>();
		domainEntities = new Object[numberOfEntities];
		this.bizz = b;

	public GenericModel cloneModel(DomainEntity[] domainToClone) {
		domainEntities = null;
		domainEntities = new Object[domainToClone.length];

		for (int i = 0; i < domainToClone.length; i++) {
			this.domainEntities[i] = domainToClone[i].copyOf();

		this.errors = new ArrayList<String>();
		return this;

	public abstract GenericModel newModel();

	public abstract boolean validateModel();

	public abstract ValidateResponse ajaxValidator(Object... toBeValidate);

	public List<String> getErrors() {
		return errors;

	public Object[] getDomains() {
		return domainEntities;


We define three fields:

  • list of errors
  • array of domain objects
  • and facade for business methods.

These fields are protected because they will be used in sub-classes which are going to be derived from this GenericModel class. Array of domain objects creates more reusable solution, because we use the same entities for db and UI representation. If we want additional fields, we can add them at specific model class.

We have constructor that is used by sub-classes, which creates empty error list, creates array of domain objects and initialize the business facade. Next method is cloneModel, which creates copy of the domain objects and empty list of errors.
Next two methods are abstract (a.k.a templates) and have their implementation is different for every model. Every model sub-class have different way of creating new model(newModel()) and validating that same model (validateModel()). Also, we have validating data from ajax request (ajaxValidator(Object… toBeValidate)). The last methods are just getters for errors and domain objects (these methods breaks the encapsulation but they are required by EL language used in jsp for data binding).

Now, lets look at concrete implementation of the generic model:

import org.ugly.entities.SignupDetails;
import org.ugly.service.facade.EJBServiceFacade;

import com.googlecode.htmleasy.playground.domain.ValidateResponse;

/** Simple POJO to store our view model. */
public class UserModel extends GenericModel {

	private Long count;

	public Long getCount() {
		return count;

	public void setCount(Long count) {
		this.count = count;

	public UserModel(EJBServiceFacade b) {
		super(b, 1);

	public GenericModel newModel() {
		this.domainEntities[0] = bizz.getAllSignupDetails().get(0);
		this.count = bizz.countSignupDetails();
		return this;

	public boolean validateModel() {
		SignupDetails domainToBeValidate = ((SignupDetails) domainEntities[0]);
		ValidateResponse response = ajaxValidator(domainToBeValidate

		if (!response.isValid()) {

		return errors.size() == 0;

	public ValidateResponse ajaxValidator(Object... toBeValidate) {
		String username = toBeValidate[0].toString();
		if (username == null || username.length() == 0) {
			return new ValidateResponse(false, "Please enter a username.");
		} else if (username.startsWith("admin") || username.equals("john")) {
			return new ValidateResponse(false,
					"This username is already taken.");
		} else if (username.length() < 4) {
			return new ValidateResponse(false,
					"Usernames must be 4 or more letters.");
		} else if (username.contains(" ")) {
			return new ValidateResponse(false,
					"Usernames must not contain spaces.");
		return ValidateResponse.VALID;


We override all methods and we implemented specific logic for all of them. New model is created from the data fetch from database, we validate our model (every UI entity implements validation method) and we create ajax validator only for username.

Whole page:

<%@ taglib prefix="c" uri="" %>
<%@ taglib prefix="fmt" uri="" %>
<%@ taglib prefix="fn" uri="" %>
<%@page import="com.googlecode.htmleasy.playground.UserModel"%>
<%@page import="com.googlecode.htmleasy.playground.UserSignup"%>

    <style type="text/css">
      #usernameMsg {color: red;}
	<script type="text/javascript" src=""></script>
	<script  type="text/javascript">
		// User JQuery to wire up call to the AJAX username validate method
		$(function () {

			$("#username").keyup(function (e) {
				var $element = $(this);
					type: "POST",
					url: "/signup/validate_username",
					data: {"username" : $element.val()},
					success: function (response) {
							if (!response.valid) {
							} else {

			// Select the sex based on the model value

	<c:out value="${pageContext.request.contextPath}" />
	<h1>New User Signup Form</h1>


		UserModel model = (UserModel) request.getAttribute("model");

		if (model.getErrors().size() > 0) {
			out.append("<div class='errorMessage'>");
			for (String error: model.getErrors()) {

	<form method="post" action="/signup">
		    <td>Username:</td><td><input id="username" type="text" name="username" value="${[0].username}"/> <span id="usernameMsg"></span><td>
		    <td>Password:</td><td><input type="password" name="password" value="${[0].password}"/></td>
		    <td>Confirm Password:</td><td><input type="password" name="confirmPassword" value="${[0].confirmPassword}"/></td>
				<select id="sex" name="sex">
					<option value="Unknown"></option>
					<option value="Male">Male</option>
					<option value="Female">Female</option>
		     <td colspan="2"><input type="checkbox" name="agreedLegal" value="true" /> I agree to the legal terms
		     <td colspan="2" style="padding-top: 1em;"><input type="submit"/></td>
    There are ${model.count} entities in DB.

Part that we are interested:

<input id="username" type="text" name="username" value="${[0].username}"/>

As you can see we use EL expression ${[0].username}. model is default referring to model in htmleasy (this can be changed), domains[n] accessing n-th domain object and username is the property of our domain object. It’s interesting because we the type of object is discovered on runtime, so expression[i] (where i is i-th domain object) is static and this is very useful for copy-paste or find-replace 🙂
Ok, that for the model part, now let’s take a look at Controller part and see the big picture.

import org.ugly.interfaces.DomainEntity;
import org.ugly.service.facade.EJBServiceFacade;

import com.googlecode.htmleasy.View;

 * @author gjorgji
public abstract class GenericController<M extends GenericModel> {

	protected M model;
	protected String returnGet;
	protected String returnFailOnPost;

	protected EJBServiceFacade bizz;

	public View defaultGet() {
		return new View(returnGet, model.newModel());

	public View defaultPost(DomainEntity[] httpDomainObject) {
		GenericModel m = (GenericModel) model.cloneModel(httpDomainObject);

		if (!m.validateModel()) {
			return new View(returnFailOnPost, m);
		return successfullPostHandler();

	protected abstract View successfullPostHandler();


As you can see from the code in GenericController we coded algorithms of GET/POST requests and we name methods default(Get/Post), because it’s default handling mechanism for GET/POST requests. There isn’t any explanation of method logic, because they are just coded algorithms previously explain. Of course, if your logic for handling GET/POST is different, then you can write your own logic.
Here is example of concrete controller

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

import org.jboss.resteasy.annotations.Form;
import org.ugly.entities.SignupDetails;
import org.ugly.interfaces.DomainEntity;
import org.ugly.service.facade.EJBServiceFacade;

import com.googlecode.htmleasy.RedirectException;
import com.googlecode.htmleasy.View;
import com.googlecode.htmleasy.playground.domain.ValidateResponse;

public class UserSignup extends GenericController<UserModel> {

	public UserSignup() {
		this.returnGet = "/WEB-INF/templates/playground/signup/form.jsp";
		this.returnFailOnPost = "/WEB-INF/templates/playground/signup/form.jsp";

	public void setBizzFacade(EJBServiceFacade b) {
		this.bizz = b;
		this.model = new UserModel(b);

	public View showSignupForm() {
		return defaultGet();

	public View processSignup(@Form SignupDetails signupDetails) {
		return defaultPost(new DomainEntity[] { signupDetails });

	public View showSignupThanks() {
		return new View("/WEB-INF/templates/playground/signup/thanks.jsp");

	 * Validate a username server-side to ensure it's suitable for the signup
	 * process.
	 * This method is exposed to the web view layer via AJAX as well as used
	 * directly in Java when processing the post.
	 * Note: Of course in a real application some of the validation in this
	 * method would be done client-side, however some tasks such as the
	 * availability of a username can only be done server-side.
	 * @param username
	 *            The username to validate.
	 * @return A response object containing the validation status and a message.
	public ValidateResponse usernameValidator(
			@FormParam("username") String username) {
		return model.ajaxValidator(new Object[] { username });

	protected View successfullPostHandler() {
		throw new RedirectException("/signup/thanks");


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s