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.

Methods:
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);
	}

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

	@Override
	public boolean validateModel() {
		SignupDetails domainToBeValidate = ((SignupDetails) domainEntities[0]);
		domainToBeValidate.validate(errors);
		ValidateResponse response = ajaxValidator(domainToBeValidate
				.getAjaxValidatorFields());

		if (!response.isValid()) {
			this.errors.add(response.getMessage());
		}

		return errors.size() == 0;
	}

	@Override
	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="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@page import="com.googlecode.htmleasy.playground.UserModel"%>
<%@page import="com.googlecode.htmleasy.playground.UserSignup"%>

<html>
<head>
    <style type="text/css">
      #usernameMsg {color: red;}
    </style>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></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);
				$.ajax({
					type: "POST",
					url: "/signup/validate_username",
					data: {"username" : $element.val()},
					success: function (response) {
							if (!response.valid) {
								$("#usernameMsg").text(response.message);
							} else {
								$("#usernameMsg").text("");
							}
						},
				});
			});

			// Select the sex based on the model value
			$("#sex").val("${model.domains[0].sex}");

		});
	</script>
</head>
<body>
	<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'>");
			out.append("<ul>");
			for (String error: model.getErrors()) {
				out.append("<li>").append(error).append("</li>");
			}
			out.append("</ul>");
			out.append("</div>");
		}
	%>

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

Part that we are interested:

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

As you can see we use EL expression ${model.domains[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 model.domains[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 javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

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;

@Path("/signup")
@RequestScoped
public class UserSignup extends GenericController<UserModel> {

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

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

	@GET
	public View showSignupForm() {
		return defaultGet();
	}

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

	@GET
	@Path("/thanks")
	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.
	 */
	@Path("/validate_username")
	@POST
	@Produces("application/json")
	public ValidateResponse usernameValidator(
			@FormParam("username") String username) {
		return model.ajaxValidator(new Object[] { username });
	}

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

}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s