Select-option with Simple Tag

If our web application make large use of lists of items to select, at they are modified quite often, could be a good idea to write a Simple Tag that take care of the job.

We want to put the item names in a list, pass the list to a Simple Tag, and let it to do the job of creating the required HTML tags.

Given this fragment of HTML code:
<form method="POST" action="selected.jsp">
    <p>Select beer characteristics:</p>
    <p>Color: 
        <select name='color'>
            <option value='light'>light</option>
            <option value='amber'>amber</option>
            <option value='brown'>brown</option>
            <option value='dark'>dark</option>
        </select>
    </p>
<input type="SUBMIT">
</form>
We want to rewrite it:
<%@ taglib prefix="st" uri="simpleTags" %>
<!-- ... -->
<form method="POST" action="selected.jsp">
    <p>Select beer characteristics:</p>
    <p>Color:
        <st:select name='color' options='${applicationScope.colors}' />
    </p>
<input type="SUBMIT">
</form>
Where "colors" is a list of colors, created somewhere else:
java.util.List<String> aList = new java.util.ArrayList<String>();
aList.add("light");
aList.add("amber");
aList.add("brown");
aList.add("dark");

application.setAttribute("colors", aList);
Our new tag is expected to be named "select", have no body, and a couple of required attribute. This is its declaration in the TLD file:
<tag>
    <name>select</name>
    <tag-class>ch10.SelectTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>options</name>
        <type>java.util.List</type>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>name</name>
        <required>true</required>
    </attribute>
</tag>
This is its implementation:
package ch10;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class SelectTag extends SimpleTagSupport {
    private List<String> options;
    private String name;

    public void setOptions(List<String> options) {
        this.options = options;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();

        // generate the HTML select open tag
        out.print("<select name=" + this.name + '>');

        // generate the required HTML option tags
        for(String option : options) {
            out.print("<option value='" + option + "'>" +
                    option + "</option>");
        }

        // generate the HTML select close tag
        out.println(" </select>");
    }
}
Simple tag handlers are discussed in chapter ten of Head First Servlet and JSP.

No comments:

Post a Comment