【问题标题】:Are there any standard JSP EL function as analog of JSTL c:url?是否有任何标准的 JSP EL 函数作为 JSTL c:url 的模拟?
【发布时间】:2013-07-04 09:01:35
【问题描述】:

我发现这段代码很丑:

<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>

【问题讨论】:

  • @BalusC 感谢伟大的链接!我研究了有关使用 base HTML 标签的问题,但发现它有很多陷阱,因为根据 W3C 规范它需要 absolute 路径,因为我们使用负载平衡代理,所以没有例外... +1
  • 该答案还显示了如何生成正确的答案。
  • 谢谢!我在 base 标记中看到 req.requestURL ))

标签: jsp jakarta-ee jstl el


【解决方案1】:

或者更好:

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

这是可能的:

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

如果您发现它很长,只需在主模板顶部的其他位置使用 &lt;c:set&gt; 为其别名,就像这样

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

这样你就可以在其他任何地方使用它

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

另见:

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    这会将URL存储在变量myUrl中,该变量可以用作a标签中的表达式。

    【讨论】:

    • 感谢您的回答,请查看我的回答,我在其中提供了更多选项。一个缺点 - 您必须将 c:url var= value= 放在每个 JSP 文件的开头... +1
    【解决方案3】:

    我对该领域的研究表明,我可以将 ctx 参数放在 web.xml 中自己的 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>
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多