Struts2 anchor tag doesn't include contextPath

孤街醉人 提交于 2019-12-07 15:20:07

问题


%{#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:


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>



回答2:


Does Struts 2 support EL?

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



来源:https://stackoverflow.com/questions/3962478/struts2-anchor-tag-doesnt-include-contextpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!