protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {List<Product> products = productService.list(); // Obtain all products.request.setAttribute("products", products); // Store products in request scope.request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.} catch (SQLException e) {throw new ServletException("Retrieving products failed!", e);}}
<!DOCTYPE taglibPUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN""http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<!-- A tab library descriptor --><taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor"><tlib-version>1.0</tlib-version><jsp-version>1.2</jsp-version><short-name>Java2s Simple Tags</short-name>
<!-- This tag manipulates its body content by converting it to upper case--><tag><name>bodyContentTag</name><tag-class>com.java2s.BodyContentTag</tag-class><body-content>JSP</body-content><attribute><name>howMany</name></attribute></tag></taglib>
将以下代码编译为WEB-在F\类\com\java 2 s
package com.java2s;
import java.io.IOException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.BodyContent;import javax.servlet.jsp.tagext.BodyTagSupport;
public class BodyContentTag extends BodyTagSupport{private int iterations, howMany;
public void setHowMany(int i){this.howMany = i;}
public void setBodyContent(BodyContent bc){super.setBodyContent(bc);System.out.println("BodyContent = '" + bc.getString() + "'");}
public int doAfterBody(){try{BodyContent bodyContent = super.getBodyContent();String bodyString = bodyContent.getString();JspWriter out = bodyContent.getEnclosingWriter();
if ( iterations % 2 == 0 )out.print(bodyString.toLowerCase());elseout.print(bodyString.toUpperCase());
iterations++;bodyContent.clear(); // empty buffer for next evaluation}catch (IOException e) {System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());e.printStackTrace();} // End of catch
int retValue = SKIP_BODY;
if ( iterations < howMany )retValue = EVAL_BODY_AGAIN;
return retValue;}}
启动服务器并在浏览器中加载bodyContent.jsp文件:
<%@ taglib uri="/java2s" prefix="java2s" %><html><head><title>A custom tag: body content</title></head><body>This page uses a custom tag manipulates its body content.Here is its output:<ol><java2s:bodyContentTag howMany="3"><li>java2s.com</li></java2s:bodyContentTag></ol></body></html>