JSP自定义标签捕获用户输入

时间:2011-07-05 11:24:56

标签: java jsp jsp-tags

如何捕获使用html表单的输入并使用自定义jsp标记将其显示在另一个jsp页面中?简单如下?


JSP页面

<%@ taglib uri="/myTLD" prefix="mytag"%>
<html>
  <title>My Custom Tags</title>
  <body>
    <form method="post" action="index.jsp">
    Insert you first name <br />
    <input type="text" name="username" />
    <input type="submit" value="Done" />
    </form>   
     <mytag:hello username="${param['username']}"/>
  </body>
</html>

WEB.XML

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <display-name>Hello</display-name>
<taglib>
     <taglib-uri>/myTLD</taglib-uri>
     <taglib-location>/WEB-INF/tld/taglib.tld</taglib-location>
    </taglib>
</web-app>

TLD文件

<?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/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<jsp-version>1.1</jsp-version>
<tlibversion>1.0</tlibversion>
<shortname></shortname>
<tag>
    <name>hello</name>
    <tag-class>com.jjolt.HelloTag</tag-class>
    <attribute>  
       <name>username</name>  
       <required>true</required>  
       <rtexprvalue>true</rtexprvalue>  
    </attribute>
</tag>
</taglib>

java class

package com.jjolt;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class HelloTag extends BodyTagSupport 
{
  private String[] username=null;
  public int doStartTag()
  {
    username = (String[]) pageContext.getAttribute("username");
    return EVAL_BODY_INCLUDE;
  }
  public int doEndTag() throws JspException 
  {
    JspWriter out = pageContext.getOut();
    try 
    {
        out.println("Hello "+username[0]);
    } 
    catch (Exception e) 
    {
    }
     return SKIP_BODY;
  }
}

1 个答案:

答案 0 :(得分:1)

我认为您误解了自定义标记的工作原理,首先需要提交表单,然后才能访问用户输入字段的内容。

所以对于你的例子你应该有这个:

<强> form.jsp

<%@ taglib uri="/myTLD" prefix="mytag"%>
<html>
  <title>My Custom Tags</title>
  <body>
    <form method="post" action="index.jsp">
    Insert you first name <br />
    <input type="text" name="username" />
    <input type="submit" value="Done" />
    </form>  
    <!-- removed tag from here -->
  </body>
</html>

<强>的index.jsp

<%@ taglib uri="/myTLD" prefix="mytag"%>
<html>
  <title>My Custom Tags Result</title>
  <body>
    <mytag:hello username="${param['username']}"/>
  </body>
</html>

现在应该可以了。