站内搜索: 请输入搜索关键词
当前页面: 图书首页 > JavaServer Pages, Second Edition

JavaServer Pages, Second Edition

[ directory ] Previous Section Next Section

Chapter 13. Creating New Tag Libraries

Since Chapter 4, we have seen that custom tag libraries are an invaluable asset. The time has now come to learn how to create new ones. Fundamentally, tags are not much more complicated than servlets; in fact, servlets could be used to construct a very limited form of custom tag. If it rendered the current time to a page, a servlet could be used almost as a "tag":

<jsp:include page="/dateServlet">
  <jsp:param name="format" value="HH:MM:SS"/>
</jsp:include>

Alternatively, if tags were implemented as servlets and held to the bean naming conventions, the page compiler could take a simple JSP:

Here is the date:
<awl:date format="HH:MM:SS"/>
<p>

and turn it into the following code:

public void service(HttpServletRequest request,
                    HttpServletResponse response)
{
    response.setStatus(res.SC_OK);
    response.setContentType("text/html");


    PrintWriter out = response.getWriter();
    out.println("Here is the date:");


    DateServlet tag = new DateServlet();
    tag.setFormat("HH:MM:SS");
    tag.service(request,response);


    out.println("<p>");
}

Including the contents of a servlet within a page using either of these approaches is not quite enough to do everything that a tag does. However, this concept will serve as a convenient jumping-off point in exploring how tag libraries are constructed.

    [ directory ] Previous Section Next Section