JSPs as Views

JSPs are just HTML, so non-programmers can work with the presentation elements.

But even simple logic is tedious (this page has more than necessary).

This JSP as View:

  • Handles requests forwarded to it.
  • Uses beans for pluggable styles.
  • Uses data in the request attributes.
  • Presents the data in HTML form.
<%@ page import="com.grdurand.LogEntry" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="style" class="com.grdurand.StyleBean" />
<html>
<head>
  <title><jsp:getProperty name="style" property = "blogTitle" /></title>
  <style type="text/css">
    div.title {<jsp:getProperty name="style" property = "title" />}
    div.entry {<jsp:getProperty name="style" property = "entry" />}
    div.stamp {<jsp:getProperty name="style" property = "stamp" />}
  </style>
</head>
<body>
<center><h1><jsp:getProperty name="style" property = "blogTitle" /></h1>
<% 
    String servletName = (String) request.getAttribute("servletName");
%>
<a href="<%= servletName %>?blogpost=true">Post a New Entry</a><p>
<% 
    LogEntry[] entries = (LogEntry[]) request.getAttribute("entries");
    
    for (int i = 0; i < entries.length; i++) {
        LogEntry entry = entries[i];
%>
    <div class=title><%= entry.title %></div>
    <div class=entry><%= entry.entry %></div>
    <div class=stamp>
        Posted on <%= new Date(entry.date) %> by <%= entry.author %>
        <br><a href="<%= servletName %>?permalink=<%= entry.id %>">
        PermaLink</a>
    </div>
    <p>
<%
    } 
%>
</body>
</html>