2011-07-05 9 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> 

をそして、それが機能するようになりました。

関連する問題