JSP custom tag library (Passing Attributes)

2019-02-27 05:58发布

I'm trying to use multiple attributes in my custom tag, e.g.:

<mytaglib:mytag firstname="Thadeus" lastname="Jones" />

How can I access the attributes in the TagHandler code?

标签: jsp-tags
3条回答
我命由我不由天
2楼-- · 2019-02-27 06:35

Not really the answer to what you asked, but I hate (ie have never written) TagHandler's but I love tag files. Lets you write custom tags using jsp files. You probably know about them and are not available/applicable - but thought I'd mention them just in case.

查看更多
ら.Afraid
3楼-- · 2019-02-27 06:37

To demonstrate the solution of this problem lets take an analogy . Suppose we have "userName" and "password" which is retrieved from index.jsp and we have to pass our data in custom tag attribute. In my case its working

<body>

<%
String name=request.getParameter("name");
String password=request.getParameter("password");
%>

<%@ taglib prefix="c" uri="/WEB-INF/mytag.tld" %>

<c:logintag name="<%=name %>" password="<%=password %>"/>

查看更多
男人必须洒脱
4楼-- · 2019-02-27 06:49

In order to access the parameters your TagHandler class should define the private members and provide accessor methods.

public class TagHandler extends TagSupport {
    private String firstName;
    private String lastName;

    public void setFirstName(String firstname) { firstName = firstname; }
    public void setLastName(String lastname) { lastName = lastname;}
}

you can then access the parameters through the TagHandler variables.

public int doStartTag() throws JspException {
    pageContext.getOut().print(lastName + ", " + firstName);
}

If you still have problems double check your naming conventions, the Java interpeter is trying to guess what the setter method is. So if your parameter is "FirstName" than the set method must be "setFirstName" if the parameter is "lastname" the set parameter must be "setlastname". I perfer to follow the former, since it is the standard Java naming convention.

查看更多
登录 后发表回答