是否有任何标准的JSP EL函数作为JSTL的模拟c:url?

时间:2013-07-04 09:01:36

标签: jsp java-ee jstl el

我发现这段代码非常难看:

<a href="<c:url value='/my/path/${id}.html'/>">Title</a>

在:

href="<c:url value=

'/>">

份。 JSP EL是否有任何标准函数,它们与JSTL c:out 的作用相同,但看起来像:

<a href="${f:context('/my/path/'.concat(id).concat('.html'))">Title</a>

或更好:

<a href="${f:context}/my/path/${id}.html">Title</a>

3 个答案:

答案 0 :(得分:2)

你可以这样做:

<c:url value='/my/path/${id}.html' var="myUrl"/>
<a href="${myUrl}">My Url</a>

这会将网址存储在变量myUrl中,该变量可用作a代码中的表达式。

答案 1 :(得分:2)

  

或更好:

<a href="${f:context}/my/path/${id}.html">Title</a>

这是可能的:

<a href="${pageContext.request.contextPath}/my/path/${id}.html">Title</a>

如果您发现它很长,只需在主模板顶部的其他位置使用<c:set>进行别名

<c:set var="ctx" value="${pageContext.request.contextPath}" scope="request" />

以便您可以在其他任何地方使用它,例如

<a href="${ctx}/my/path/${id}.html">Title</a>

另见:

答案 2 :(得分:1)

我对这个领域的研究表明,我可以在 web.xml 中将 ctx 参数放在自己的EE过滤器中:

<filter>
    <filter-name>ctxFilter</filter-name>
    <filter-class>org.my.web.filter.CtxFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>ctxFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

public class CtxFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) { }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setAttribute("CTX", request.getServletContext().getContextPath());
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() { }
}

或在Spring拦截器中(基于我的项目框架堆栈)。这也可以通过以下方式完成:

<spring:url value="/" var="ctx" htmlEncoding="true"/>
<a href="${ctx}/path/...">...</a>

或作为:

<c:url value="/" var="ctx"/>
<a href="${ctx}/path/...">...</a>

但必须在JSP文件中复制这些示例的第一行。

最后,您可以使用适当的功能实现TDL文件 WEB-INF / tlds / ctx.tld

<function>
    <name>ctx</name>
    <function-class>org.my.web.Ctx</function-class>
    <function-signature>java.lang.String getCtx()</function-signature>
</function>

参考:

相关问题