简体   繁体   中英

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?

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

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"%>
<%@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM