Alex
Alex

Reputation: 743

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

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

Upvotes: 3

Views: 8841

Answers (1)

BalusC
BalusC

Reputation: 1108722

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

Upvotes: 3

Related Questions