Bass
Bass

Reputation: 5338

Injecting JSP EL and/or JSTL tags from Java code

I have Java classes which are used on a JSP page. getAttr() returns a string with an arbitrary number of HTML anchor elements leading to URLs local to my web application:

public class C {
    public String getAttr() {
        return "foo <a href = \"/index.html\">bar</a> baz";
    }
}

and

<c:set var = "c" value = "..."/>
${c.attr}

As long as the default context (/) is used, everything's fine. Non-default contexts can be accounted for by using smth like <a href = "<c:url value = "..."/>">...</a>, but this is JSP-specific. JSTL/EL injection from Java code like return "<a href = \"<c:url value = \"...\"/>\">...</a>"; doesn't (and shouldn't) work.

How can I support non-default context without exposing the internals of my Java classes? Manual hyperlink creation outside of JSP scope is at least ugly, but I've run out of ideas.

Upvotes: 0

Views: 504

Answers (1)

GUISSOUMA Issam
GUISSOUMA Issam

Reputation: 2582

Try to get HttpServletRequest in your Class c:

public class C {

    private HttpServletRequest request;
    //initialize request in a constructor

    public String getAttr() {
        return "foo <a href = \""+request.getContextPath()+"/index.html\">bar</a> baz";
    }
}

Upvotes: 1

Related Questions