tags:

views:

85

answers:

2

%{#request.contextPath} doesn't work inside an s:a tag in Struts2. (Struts 2.2.1 to be specific.) Is there a way to make it work? It works in other Struts2 tags.

Here are two lines in a JSP file in a Struts 2 project whose context path is "/websites":

<s:a href="%{#request.contextPath}/clickme" theme="simple">Click here.</s:a>
<s:form method="post" action="%{#request.contextPath}/submitme" theme="simple"></s:form>

And here is the output:

<a href="/clickme">Click here.</a>
<form id="submitme" name="submitme" action="/websites/submitme" method="post"></form>

Notice that the context path is left off the anchor but is included in the form.

P.S. I can't use ${#pageContext.request.contextPath} here because ${} isn't allowed in Struts2 tags. Besides, I'm trying to be consistent. And I also try generally to avoid ${} since it does not auto-escape the output.

Thanks!

+1  A: 

Does Struts 2 support EL?

You can use ${request.contextPath} if it does....

The Elite Gentleman
Struts tags use OGNL expressions
Samuel_xL
AAah, ok...JSP 2.0 supports EL, so the OP can use it with his Struts 2 tag (or can't it?). I clearly remember using EL with Struts 1.3.6 and higher....
The Elite Gentleman
I mentioned in the P.S. part of the question that I can't use the `${}` syntax in a Struts 2 tag and that I tend to avoid it because it doesn't auto-escape the output.
Brian Morearty
Your PS probably came later (after I wrote this). I'll try and see if Struts 2 support `EL` under JSP 2.0 and higher.
The Elite Gentleman
A: 

This should work:

<s:set id="contextPath"  value="#request.get('javax.servlet.forward.context_path')" />
<s:a href="%{contextPath}/clickme" theme="simple">Click here.</s:a>

However, you're not supposed to do this. When you need an url, use the <s:url> tag:

<%-- Without specifying an action --%>
<s:url id="myUrl" value="clickme" />
<s:a href="%{myUrl}" theme="simple">Click here.</s:a>

<%-- With an action --%>
<s:url id="myUrl" action="clickme" />
<s:a href="%{myUrl}" theme="simple">Click here.</s:a>

By the way, you don't need a context path for the action attribute of a form:

<s:form method="post" action="submitme" theme="simple"></s:form>
Samuel_xL
Thanks. I had tried `<s:set id="contextPath" value="#request.contextPath" />` without success but hadn't tried your version. But in the end I used `<s:url />` like this: `<a href="<s:url value="clickme" />"Click here</a>` Also used a global setting to set the `includeParams` attribute to "none" by default.
Brian Morearty