Ali
Ali

Reputation: 267049

How to include a variable in a jsp tag?

I'm trying to dynamically include a jsp file with the following code:

<%@include file="menus/top/${user.roleId}.jsp" %>

Here, the variable user.roleId is an int which is being set in my struts2 action. I'm able to display it with the following:

<s:property value="user.roleId" />

I want the files menus/top/1.jsp, or menus/top/2.jsp etc to be included dynamically, depending on the roleId of the currently logged in user. But I'm getting the following exception with the include tag:

Exception Name: org.apache.jasper.JasperException: File "menus/top/${user.roleId}.jsp" not found 

What am I doing wrong?

Upvotes: 2

Views: 6212

Answers (3)

coding_idiot
coding_idiot

Reputation: 13714

<%@include file="menus/top/${user.roleId}.jsp" %>

Use struts2 include tag instead

<s:include file="menus/top/%{user.roleId}.jsp"/>

Documentation clearly says include directive is not processed and hence, can't have expressions that needs runtime evaluation.

Upvotes: 3

Trying
Trying

Reputation: 14278

use <c:import> tag. As it is used for dynamic include in JSTL.

where c :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

<%@include %> is a static include directive. It's thus used at compile time, when the JSP is compiled into a class. This implies that runtime variables can't be used inside this directive.

You're looking for <jsp:include>, which includes a resource dynamically, at runtime. Read this tutorial for more details.

Upvotes: 4

Related Questions