While trying to iterate a map in a javascript function by passing key as below:
<html> <head>
<script type="text/javascript">
function demo(tmp){
<c:forEach var="user" items="${usermap}">
<c:out value="${usermap.get(\"+'tmp'+\").name}"></c:out>
</c:forEach>
}
</script>
<title>Insert title here</title> </head>
<body>
<h1 onclick="demo('user1')">User VO</h1>
<c:forEach var="user" items="${usermap}">
Key: ${user.key} - Name: ${user.value.name} - Id: ${user.value.userid}<br/><br/>
</c:forEach>
</body> </html>
I am getting blank value. But when I hard code the value of key***user1***, it works.
Servlet Code protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub
//System.out.println("in servlet doGet:"+ ++count);
UserVO user1= new UserVO("Y","701");
UserVO user2= new UserVO("D","834");
hmap.put("user1", user1);
hmap.put("user2", user2);
//hmap.values()
request.setAttribute("usermap", hmap);
//response.sendRedirect("User.jsp");
RequestDispatcher view = request.getRequestDispatcher("User.jsp");
view.forward(request, response);
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
Can somebody help me here?
The Issue:
You are mixing client side and server side code. JavaScript and JavaServer Pages are executed separately.
So JSP related stuff like:
<jsp:something>
<c:something>
)${something}
)is processed on the server.
You can see, what HTML code is received in browser, by pressing
Ctrl+U
in Firefox/Chrome.In your case:
Selecting an option in the select-tag is executed on the client side in browser.
It is too late for EL-evaluation. The EL has bean already evaluated.
You can use ajax to request the needed data (map) according the user selection.
EDIT:
The EL of the hardcoded line is executed on the server and replaced with the value. On the other case, when select-tag is involved, the EL was executed on the server and replaced by
var Cfs_id ="";
. So the dummy function ignore the parameter serviceId and set the variable always to empty string.Look the code in your browser. There is only Html and Javascript. The JSP EL are no more there.