Use tag attributes in java code in jsp tag file

6.5k views Asked by At

I have some attributes declared by something like <%@attribute name="listname" required="true"%> in the starting in .tag file.

I can print that by using ${listname}. But I want to use this variable in one of the java code inside the same page.

Something like,

<%
    String listname = ${listname};
    ...Some more code...
%>

How do I do this.

I am using apache tomcat6 if that helps.

I am new to this environment and even Java. Please forgive and correct me if I am using some wrong terminologies.

2

There are 2 answers

0
Andy Senn On

Have you looked into doing the processing in a Java class instead of a JSP? The configuration is a little bit different than using .tag files:

web.xml

<jsp-config>
    <taglib>
        <taglib-uri>mytaglib</taglib-uri>
        <taglib-location>/WEB-INF/tags/mytaglib.tld</taglib-location>
    </taglib>
    ...
</jsp-config>

mytaglib.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">

    <tlib-version>1.0</tlib-version>
    <short-name>mylib</short-name>
    <uri>/WEB-INF/tags/mytaglib</uri>
    <tag>
        <name>checkbox</name>
        <tag-class>com.myapp.tag.MyTagSupport</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>name</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        ...
    </tag>
    ...
</taglib>

JSP Include

<%@taglib uri="mytaglib" prefix="ml" %>

Tag Support Class

package com.myapp.tag;

import javax.servlet.jsp.tagext.BodyTagSupport    

public class MyTagSuppoort extends BodyTagSupport {

    private String name = name;

    // Values are autowired by the JSTL API
    public void setName ( String name ) {
        this.name = name;
    }

}

This is a decent example of how to implement things in your tag support class too:

http://www.tutorialspoint.com/jsp/jsp_custom_tags.htm

0
Emerald Icemoon On

You can get at attributes passed to custom tags using the attributes from jspContext :-

<%@ tag description="Category Options" trimDirectiveWhitespaces="true"  pageEncoding="UTF-8" %>
<%@ attribute name="depth" required="false" type="java.lang.Integer" rtexprvalue="true"%>

<%
Integer depth = (Integer)jspContext.getAttribute("depth");
// do stuff with depth
%>