adam bien's blog

The Return Of JSPs In HTML 5? 📎

In it's early days JSPs were misused for the realization of business logic. Any complex code enclosed in scriplets is hard to write, test and so maintain.

However: JSPs are perfectly suitable for delivery of HTML 5 documents:

  1. You have full control over HTML markup. There is no hidden code generation in place.
  2. No magic: JSPs become Servlets. Usually you can even look at the generated code in case something feels strange.
  3. After the initial invocation, JSPs are as performant as Servlets.
  4. JSPs just serve strings, so no components have to be hold in memory -- the memory requirements are low.
  5. IDE support, debugging and performance analytics for JSPs are superb.
  6. JSPs even support lambdas in EL.
  7. JSPs can be perfectly used in the "logic free" mode, just as a powerful templating language.
  8. You can introduce custom tags for the encapsulation of recurring functionality.
  9. CDI managed beans and so whole Java EE components can be easily exposed to JSPs

A simple POJO:


public class Greeting {

    private String title;
    private String content;

    public Greeting(String title, String content) {
        this.title = title;
        this.content = content;
    }
    public String getTitle() {
        return title;
    }
    public String getContent() {
        return content;
    }
}

Could be easily exposed by a CDI presenter / backing bean:

@Model
public class Index {

    public List<Greeting> getGreetings() {
        List<Greeting> greetings = new ArrayList<>();
        greetings.add(new Greeting("short", "hi"));
        greetings.add(new Greeting("casual", "hello"));
        greetings.add(new Greeting("formal", "welcome"));
        return greetings;
    }
}

...and conveniently rendered using a JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<body>
    <h1>Hello JSP</h1>
    <ul>
        <c:forEach var="message" items="${index.greetings}">
    	    <li><c:out value="${message.title}"/> - <c:out value="${message.content}"/></li>
        </c:forEach>
    </ul>
</body>

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!