2011-07-05 66 views
0

如何捕獲使用來自html表單的輸入並使用自定義jsp標籤將其顯示在另一個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類

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

我想你誤會了自定義標籤是如何工作的,您首先需要提交表單,只有在此之後,你能夠訪問用戶輸入字段的內容。

因此,對於你的例子中,你應該有這樣的:

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> 

現在它應該工作。

相關問題