开发者

JSP Custom Tags capture user input

How 开发者_运维问答would one capture use input from html form and display it in another jsp page using a custom jsp tag? a simple like the following?


JSP page

<%@ 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 file

<?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;
  }
}


I think you misunderstood how custom tags works, you first need to submit the form, only after this you are able to access the contents of the user input fields.

So for your example you should have this:

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>

And it should work now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜