Vinayak Bevinakatti
Vinayak Bevinakatti

Reputation: 40503

JSP custom tag library (Passing Attributes)

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?

Upvotes: 2

Views: 4756

Answers (3)

Sachindra N. Pandey
Sachindra N. Pandey

Reputation: 1242

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 %>"/>

Upvotes: -1

LizB
LizB

Reputation: 2213

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.

Upvotes: 4

Chris Kimpton
Chris Kimpton

Reputation: 5541

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.

Upvotes: 0

Related Questions