Friday, June 22, 2018

How to access JSTL variable in Scriptlets


Sometimes we have a situation in which we need to access JSTL in our scriptlets. Today we will solve this problem. Here i need to call a simple method greetUser that take screen name as a argument.

Problem
When we try to access this we have the errors like:-
<%@page import="com.test.Demo"%>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="java.util.List"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%
List<User> userList = UserLocalServiceUtil.getUsers(1, 5);
request.setAttribute("userList", userList);// put in request so that we can access this in EL
%>
<c:forEach items="${userList}" var="user">
Greetings :- <%=Demo.greetUser(user.getScreenName()) %><br> // Error
OR
Greetings :- <%=Demo.greetUser(${user.screenName}) %><br> // Error
OR
Greetings :- <%=Demo.greetUser(<%=user.screenName%>) %><br> // Error
</c:forEach>
view raw problem.jsp hosted with ❤ by GitHub


Solution
For solving this situation we first put the screenName in pageContext using c:set and then use this to call out method.

<%@page import="com.test.Demo"%>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="java.util.List"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%
List<User> userList = UserLocalServiceUtil.getUsers(1, 6);
request.setAttribute("userList", userList);// put in request so that we can access this in EL
%>
<c:forEach items="${userList}" var="user">
<c:set var="screenName" value="${user.screenName}" scope="page" />
<%
String screenName = String.valueOf(pageContext.getAttribute("screenName"));
String greetName = Demo.greetUser(screenName);
%>
Greetings :- <%=greetName %><br>
</c:forEach>
view raw solution.jsp hosted with ❤ by GitHub




Hope this will Help....

Related Post:-

No comments:

Post a Comment

Total Pageviews

1041868

Number Of Unique Visitor

Free counters!