tags:

views:

1006

answers:

4

I'm writing a custom JSP tag using the JSP 2 tag files. Inside my tag I would like to know which page called the tag in order to construct URLs. Is this possible with out passing it through an attribute?

+1  A: 

I think that within the tag code, you can examine the request object and its url, and determine the page from that.

Yoni
The request object would work if this was a regular JSP page but inside the tag file the request object is not available.
timdisney
A: 

Turns out that the request object actually is available, but only in the EL portion of a tag. So this would work:

<form action="${pageContext.request.requestURI}">

But not this:

<form action="<%=request.requestURI%>">

Or this:

<form action="<%=pageContext.request.requestURI%>">
timdisney
A: 

It is possible to access the request from within the tag file, via the pageContext member variable.

public class YourTag extends TagSupport {
    public int doStartTag() throws JspException {
        HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
        String pathInfo = req.getPathInfo();
Johann Zacharee
A: 

The request object is available in the tag. It doesn't matter if you use a class or a tag file. In tag files, it is available in Java scriptlets as well as in EL. However, it is available as a ServletRequest object and not an HttpServletRequest object (in EL the class of the object doesn't matter, but it does in scriptlets).

In addition, in your scriptlets you need to access the full method, not just a property name. So your code is supposed to be:

<form action="<%= pageContext.getRequest().getRequestURI() %>">

but even that won't work because getRequestURI() is a method of HttpServletRequest [1], not of ServletRequest. So either use EL, or use longer scriptlets in your tag file and cast the request object.

[1] http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI()

Yoni