开发者

JSP - using a variable as the url in c:import

开发者 https://www.devze.com 2023-03-21 16:04 出处:网络
Is there any way that we can use a variable in a <c:import> statement in JSP such as: <c:import url=\"<%=_header%>\"></c:import>, where _header is a JSP String defined thus;

Is there any way that we can use a variable in a <c:import> statement in JSP such as: <c:import url="<%=_header%>"></c:import>, where _header is a JSP String defined thus;

// host will typically equal: uk.domain.com or fr.domain.com
String host = request.getServerName();
// cc is attempting to become the country code for the domain
String cc = host.substring(0, host.indexOf("."));

String _header = "http://assets.domain.com/" + cc + "/includes/header_" + cc + ".jsp";

We host a number of sites across multiple markets. Being able to define one template this way would be ideal as it would mean fewer changes to templates. Unfortunately whenever including <c:import url="<%=_header%>"></c:import> the server fails to load the page.

But including, for instance: <c:import url="http://assets.domain.com/uk/includes/header_uk.jsp?market=<%=cc%>"></c:import> seems to work fine.开发者_开发问答..

Any thoughts?!


Edit: Turns out the <%=cc%> var in the URL wasn't actually working. Had to do the following instead to get it to work;

String cc = host.substring(0, host.indexOf("."));
session.setAttribute("cc", cc);

...

<c:import url="http://assets.domain.com/uk/includes/header_uk.jsp"><c:param name="market">${cc}</c:param></c:import>

Still haven't solved the variable URL problem yet, however...


You can't reliably mix scriptlets with taglibs/EL. They runs in different moments and scopes. You should choose to use the one or the other. Since the use of scriptlets is officially discouraged since JSP 2.0 (released Nov 2003), I'd recommend to drop it altogether and go ahead with taglibs/EL only.

The following scriptlet

<%
    // host will typically equal: uk.domain.com or fr.domain.com
    String host = request.getServerName();
    // cc is attempting to become the country code for the domain
    String cc = host.substring(0, host.indexOf("."));
%>

can be replaced by the following taglib/EL:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:set var="cc" value="${fn:split(pageContext.request.serverName, '.')[0]}" />

so that it's available as ${cc} in EL.

<c:import url="http://assets.domain.com/${cc}/includes/header_${cc}.jsp" />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号