Programmer, solution architect, user group and conference organizer, conference speaker and traveling fun code evangelist. Johannes tries to apply Agile principles to large software projects, but what he's really passionate about is sharing the experience of more fun programming with other coders around the world. Johannes is a DZone MVB and is not an employee of DZone and has posted 37 posts at DZone. You can read more from them at their website. View Full User Profile

A jQuery Inspired Server Side View Model for Java

05.09.2013
| 3428 views |
  • submit to reddit

In HTML applications, jQuery has changed the way people thing about view rendering. Instead of an input or a text field in the view pulling data into it, the jQuery code pushes data into the view. How could this look in a server side situation like Java?

In this code example, I read an HTML template file from the classpath, set the value of an input field and append more data based on a template (also in the HTML file).

public class ContactServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String nameQuery = req.getParameter("nameQuery");
 
        // Read a pure html template from the classpath
        Xhtml document = Xhtml.fromResource(getClass().getResource("html/contact/index.html"));
 
        // Set the value of the nameQuery input field in the HTML
        document.getForm("#findForm").set("nameQuery", nameQuery);
 
        Element contactsEl = document.select("#contacts");
        Element contactTmpl = contactsEl.take(".contact");
        for (Contact contact : findContacts(nameQuery)) {
            // Fill in the .contact template of the HTML with data
            Element contactHtml = contactTmpl.copy().text(contact.print());
            // And add it to the #contacts element
            contactsEl.add(contactHtml);
        }
 
        document.write(resp.getWriter());
        resp.setContentType("text/html");
    }
}

This is a simplified version of the HTML:

<html>
  <form method='get' id="findForm">
	<input type='text' name='nameQuery' value='null' />
    <input type='submit' name='findContact' value="Find contact" />
  </form>
  <ul id='contacts'>
    <li class='contact'>Johannes (4444444)</li>
  </ul>
</html>

This is a third way from the alternatives of templated views like Velocity and JSP and from component models like JSF. In this model, the view, the model and the binding of the model variables to the view are all separate.

Disclaimer: In this example, I’ve used my still in pre-alpha XML library with the working name of Eaxy. You can get similiar results with libraries like jSoup and JOOX.

Caveat: I’ve never tried this on a grand scale. It’s an idea that compels me for three reasons: First, it’s very explicit. Nothing happens through @annotation, conventions or some special syntax in a template. Second, it’s very unit testable. There is nothing tying this code to running in a web application server. Finally, it’s easy to get to this code through incremental steps. I initially wrote the example application with code that embedded the HTML as strings in Java code and refactored to use the Java Query approach.

Could this approach be worth trying out more?

Published at DZone with permission of Johannes Brodwall, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Mitja Gustin replied on Thu, 2013/05/09 - 5:33am

Nice article. I would say, that the best thing here is the fact, that you have your HTML files in pure html, so that you can design and develop them in dedicated HTML authoring tools. If you get rid of the man in the middle (JSP, JSF syntax) you have reduced complexity of your J2EE application for one level (everybody knows that JSP is a XML file, that gets compiled to class; and the class is outputting HTML as a side product).

What is missing here is caching of the HTML files (do not load them in each request). HTML templates are static, so you can save them to application scope'd cache.

But on the end, I must say that this idea, to have views and their controller logic on server, is around 15 years old and survived. I believe that Java on server should be only about domain logic,  system integration, database access, middle tier business logic and integrations.

See for example this great article http://ejohn.org/blog/javascript-micro-templating/. Fully functional html templates in 20 lines of code.

Regards, Mitja Gustin
gustinmi [at] gmail [dot] com 

Johannes Brodwall replied on Fri, 2013/05/10 - 2:48am in response to: Mitja Gustin

Thank you for your comment, Mitja.

I totally agree with your remarks. I left out the caching to avoid introducing more concepts in this article, but when I've experimented with it, I have it in place.

I agree that view processing really should happen on the client, so my idea here is at least a few years late. I am probably fighting yesterday's battle, but I couldn't sleep without sharing the idea. :-)

Lund Wolfe replied on Sun, 2013/05/12 - 2:23am

Reading request parameters and reading/writing form elements is built-in to Struts2, and probably other web frameworks, these days.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.