View Helper Design Pattern in Java

View Helper Pattern separates the static view such as JSP's from the processing of the business model data.
Frameworks like Spring and Struts provide their own tag libraries to encapsulate processing logic in a helper instead of a view such as JSP files.
For example,
  • Struts framework provides Tag libraries that allow you to build the view part of the MVC without embedding Java code directly within your application JSPs.
  • Spring Framework provides some tags for form bindings, spring security tabs, evaluating errors, setting themes and outputting internationalized messages.
Let's look at the example of Spring form tags In HTML form, you use spring:form tag and bind the controller object via modelAttribute.
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form method="post" modelAttribute="userForm" action="${userActionUrl}">
   <form:input path="name" type="text" />
   <!-- bind to user.name-->
   <form:errors path="name" />
</form:form>
This pattern is divided into a number of sections for simplicity like problem, forces, structure, solution, implementation etc.
Table of contents
Problem
Forces
Solution
Explanation
Structure - Class Diagram, Sequence Diagram
Participants and Responsibilities
Implementation
Consequences
Applicability
Real world examples
References

Problem

(Problem section describes the design issues faced by the developer)
You want to separate a view from its processing logic. Mingling control logic, data access logic and formatting logic within view components lead to problems with modularity, reuse, maintenance, and role separation.

Forces

(This section describes Lists the reasons and motivations that affect the problem and the solution. The list of forces highlights the reasons why one might choose to use the pattern and provides a justification for using the pattern)
You want to use template-based views, such as JSP. You want to avoid embedding program logic in the view. You want to separate programming logic from the view to facilitate division of labor between software developers and web page designers.

Solution

(Here solution section describes the solution approach briefly and the solution elements in detail)
Use Views to encapsulate formatting code and Helpers to encapsulate view-processing logic. 
  • A View delegates its processing responsibilities to its helper classes, implemented as POJOs, custom tags, or tag files. 
  • Helpers serve as adapters between the view and the model, and perform processing related to formatting logic, such as generating an HTML table.
The JavaServer Pages Standard Tag Library [JSTL] provides a standard set of tags that support common needs, such as iteration and conditional logic. Using these tags lets you avoid embedding processing logic in the form of scriptlet code in the JSP.
Developing your own helpers, either as custom tags or tag files, will provide benefits too, offering higher-level abstractions that more clearly communicate the intent of your code. Whether you use JSTL or create custom tags, however, the goal is to avoid using helpers as scriptlets. I have created a custom tag you will see in source code section.

Structure

We used UML class diagram to show the basic structure of the solution and the UML Sequence diagram in this section present the dynamic mechanisms of the solution. 
Below is the class diagram representing the relationships for the View Helper Design Pattern.

Class diagram

Sequence Diagram

Participants and Responsibilities

Client - A Client dispatches to the View.
View - A View represents and displays information to the Client. The information that is used in a dynamic display is retrieved and converted from a presentation model by helpers.
Helper1, Helper2 - A helper encapsulates processing logic for generating and formatting a View. A helper typically adapts a PresentationModel for a view or provides access to the raw data of the PresentationModel. A view works with any number of helpers, typically implemented as Java- Beans, custom tags, or tag files.
PresentationModel - The PresentationModel holds the data retrieved from the business service, used to generate the View.

Implementation

There are many strategies for this pattern to be used.
JavaBean Helper Strategy
The helper is implemented as a JavaBean. Using helpers results in a cleaner separation of the view from the business, processing, and formatting logic in an application since this logic is factored out of the view and into the helper components.
<jsp:useBean id="welcomeHelper" scope="request"
   class="corepatterns.util.WelcomeHelper" />
<HTML>
   <BODY bgcolor="FFFFFF">
      <c:if test = "${welcomeHelper.nameExists == true}">
         <center>
            <H3>
               Welcome 
               <b>
                  <c:out value='${welcomeHelper.name}'/>
               </b>
               <br><br> 
            </H3>
         </center>
      </c:if>
      <H4>
         <center>Glad you are visiting our site!</center>
      </H4>
   </BODY>
</HTML>
The problem with this strategy is that it is difficult to effectively extract implementation details from the view.
Custom Tag Helper Strategy
The helper is implemented as a custom tag, which adapts the model for use by the view. Using the Custom Tag Helper strategy requires more upfront work than the JavaBean Helper strategy since custom tag development is moderately complicated.
In this example, we are going to create a custom tag that prints the current date and time. We are performing action at the start of tag
To create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag(). To write data for the jsp, we need to use the JspWriter class.
public class MyTagHandler extends TagSupport {
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut(); //returns the instance of JspWriter  
        try {
            out.print(Calendar.getInstance().getTime()); //printing date and time using JspWriter  
        } catch (Exception e) {
            System.out.println(e);
        }
        return SKIP_BODY; //will not evaluate the body content of the tag  
    }
}
Let's create the TLD file. Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory.
<?xml version="1.0" encoding="ISO-8859-1" ?>  
<!DOCTYPE taglib  
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  
    "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">  
  
<taglib>  
  
  <tlib-version>1.0</tlib-version>  
  <jsp-version>1.2</jsp-version>  
  <short-name>simple</short-name>  
  <uri>http://tomcat.apache.org/example-taglib</uri>  
  
<tag>  
<name>today</name>  
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>  
</tag>  
</taglib> 
Create the JSP file and let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of the full path of tld file. We will learn about uri later.
It uses taglib directive to use the tags defined in the tld file.
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>  
Current Date and Time is: <m:today/>

Consequences

  • Improves application partitioning, reuse, and maintainability
  • Improves role separation
  • Eases testing
  • Helper usage mirrors scriptlets

Real world examples

References

Related Presentation Tier Posts

Comments