concepts about JSTL - java

I want to understrand what happens when i use JSTL to access maps,in Hidden features of JSP/Servlet
in #blausC's answer, he explained what happend, but when i try to use the following code
<c:set var="resultMap" value="validationResults" scope="request"></c:set>
<c:if test="${resultMap['userName'] != null}">
${resultMap['userName'].details}
</c:if>
a confused exception happend
Caused by: javax.el.PropertyNotFoundException: Property 'userName' not found on type java.lang.String
The key of the map should be string, so whay is this exception, i tried the examples in the above question and the same exception,Can some one tell me where I have misunderstanding?
Edit: I populate the map in the servlet and send it to jsp
Map<String, ValidationResult> result = new HashMap<String, ValidationResult>();
aValidationResult = new ValidationResult();
check whether the field is valid or not if not fill the map
result.put("userName", aValidationResult);
result.put("group", aValidationResult);
if map is not empty, return the map to jsp
request.setAttribute("validationResults", result);
the map is filled when i make server side validation ,
Thanx in advance.

resultMap is a String because of this line
<c:set var="resultMap" value="validationResults" scope="request"></c:set>
You need to use EL to assign the value
<c:set var="resultMap" value="${validationResults}" scope="request"></c:set>
Edit: The following is working code
<c:set var="validationResults" value="<%= new java.util.HashMap() %>" />
<c:set target="${validationResults}" property="username" value="Hello World" />
<c:set var="resultMap" value="${validationResults}" />
<c:out value="${resultMap['username']}"></c:out>

This is caused because String class does not have a method called getUserName()

Related

Accesssing model attribute in JPA doesn't work

I am having problems accessing a model attribute in my controller, using Spring.
When adding to the model, I write the status code as a key and the enumeration name as a value. The status code is e.g. AVAILABLE, NOTAVAILABLE, etc.:
String code = status.getCode();
String enumerationName = enumerationService.getEnumerationName(status, currentLocale);
model.addAttribute(code, enumerationName);
On my JPA page, I am trying to access the corresponding value using the key (status code, e.g. AVAILABLE):
<div data-availability>
<c:forEach items="${StockLevelDeliveryStatus.values()}" var="status">
<c:set var="textStyle" value="text-success" />
<c:if test="${status.code.toLowerCase() == 'notavailable'}">
<c:set var="textStyle" value="" />
</c:if>
<div class="d-none display-22 pb-2 ${textStyle}" data-availability-item data-${status.code.toLowerCase()}>
${status}
</div>
</c:forEach>
</div>
For example, the value of status is AVAILABLE and this is what is output in ${status}. However, I want the value AVAILABLE to be used as a key to return me the correct value that I set in the model above. If I change the ${status} statement to, say, ${AVAILABLE} instead, which is the concrete key, the appropriate value from the model is returned:
<div class="d-none display-22 pb-2 ${textStyle}" data-availability-item data-${status.code.toLowerCase()}>
${AVAILABLE}
</div>
If I understand it correctly, then instead of passing the enum value as a key, I need to somehow teach Spring to search in the model for the appropriate key.
As recommended in one of the replies, I also tried writing the Map<StockLevelDeliveryStatus, String> directly into the model:
Map<StockLevelDeliveryStatus, String> statusMap = new HashMap<StockLevelDeliveryStatus, String>();
for (StockLevelDeliveryStatus status : StockLevelDeliveryStatus.values()) {
statusMap.put(status, enumerationService.getEnumerationName(status, currentLocale));
}
model.addAttribute("statusMap", statusMap);
And the JSP accordingly:
<div data-availability>
<c:forEach items="${StockLevelDeliveryStatus.values()}" var="status">
<c:set var="textStyle" value="text-success" />
<c:if test="${status.code.toLowerCase() == 'notavailable'}">
<c:set var="textStyle" value="" />
</c:if>
<div class="d-none display-22 pb-2 ${textStyle}" data-availability-item data-${status.code.toLowerCase()}>
${statusMap[status]}
</div>
</c:forEach>
</div>
Here it already fails when accessing the model, because with this approach I do not get any output on the JSP.
Does anyone have any ideas on how to make this work?
Why not simply put a Map<StockLevelDeliveryStatus, String> into the model? You could then simply use ${statusMap[status]}.

JSTL nested forEach Lists throwing error

I am trying use JSTL on an old project where I have to use nested forEach.
My requirement is for example to iterate through a countries list, where each country will have a StateList which will contain State details.
<c:forEach items="${countryList}" var="country">
<c:out value="${country.name}" escapeXml="true" />
<c:forEach items="${country.StateList}" var="state">
<c:out value="${state.name}" escapeXml="true" />
</c:forEach>
</c:forEach>
When I try these I am getting error.
An error occurred while evaluating custom action attribute "items" with value "${country.StateList}": Unable to find a value for "StateList" in object of class "com.pack.Country" using operator "." (null)
What I am doing wrong? Is there a alternate method to do the same without using scriplets?
Issue Solved : The problem was that i used StateList instead of stateList as list name in class. Thanks.

passing string array as hidden value from one jsp to another jsp

I am trying to pass String array from one jsp to another. I am using JSTL in my JSP.
In my first JSP i am doing like this
<c:if test="${fn:length(empBean.additionalEmailAddr) gt 0}">
<c:forEach begin="0" end="${fn:length(empBean.additionalEmailAddr) - 1}" var="ind" >
<input type="hidden" name="inbdAdditionalEmailAddr" value="${empBean.additionalEmailAddr[ind]}"/>
</c:forEach>
</c:if>
and trying to access the values in another jsp as follows
<%
String[] inbdAddEmlAddr = request.getParameter("inbdAdditionalEmailAddr");
%>
and i am planning to use JSTL to print the array values.
In the second jsp i am getting type mismatch error. Please help.
Is this the right approach ? Any help is appreciated
Thanks
request.getParameter() returns a String which the code attempts to assign to a String[], causing the exception.
Use request.getParameterValues('inbdAdditionalEmailAddr'); to retrieve parameters as an array.
See the documentation.

Concatenating JSTL

I have a HashMap in the controller:
HashMap<String, ArrayList<String> map = new HashMap<String, ArrayList<String>();
In the JSP page I want to access this through something like this:
<c:forEach var="list" items="${requestScope.list}">
<c:set var="testing" value="{requestScope.map}"></c:set>
<c:forEach var="anotherTesting" items="${testing['${list.item}']}">
<option><c:out value="${anotherTesting}"/></option>
</c:forEach>
</c:forEach>
Where list.item is a String but it is used for another process but I want it to be used to access the HashMap.
Is there a way to concatenate JSTL? Either map.key or map['key'] will do.
I guess simply this would work:
<c:forEach var="anotherTesting" items="${testing[list.item]}">
<option><c:out value="${anotherTesting}"/></option>
</c:forEach>
Notice the difference with and without quotes:
${testing[list.item]} is equivalent to testing.get(list.getItem());
${testing['list.item']} is equivalent to testing.get("list.item");.
Some Note:
You don't need to specify the scope to access the attributes, unless there is a conflict with the same name in different scopes. So, "${requestScope.list}" can be changed to ${list}, and "${requestScope.map}" can be changed to ${map}.
Please use a different name for var attribute of outer loop. May be listItem instead of list.
No need to set the map to a different variable. That <c:set...> is not needed. You can directly access the property of map attribute.
So, your loop can be modified to:
<c:forEach var="listItem" items="${list}">
<c:forEach var="anotherTesting" items="${map[listItem.item]}">
<option><c:out value="${anotherTesting}"/></option>
</c:forEach>
</c:forEach>
The code in ${...} is not JSTL but Expression Language. You don't need to c̶o̶n̶c̶a̶t̶e̶n̶a̶t̶e̶ nest EL ${} expressions, just add it cleanly.
Knowing this, the expression ${testing['${list.item}']} will be ${testing[list.item]}.
BUT note that this is not what you really want/need unless testing is indeed a Map<String, ArrayList<String>>, otherwise you will get unexpected results. From your code above, assuming requestScope.list is a List<Map<String, ArrayList<String>>>, then the code would be:
<c:forEach var="listItem" items="${list}">
<c:forEach var="innerString" items="${map[listItem.item]}">
<option><c:out value="${innerString}"/></option>
</c:forEach>
</c:forEach>
Note that ${list} is the same as ${requestScope.list} assuming there's no list attribute nor in page, session or application scope, similar for ${map}.

Using JSTL how to "put" a value into a HashMap

I'm looking to set the key value pairing of a HashMap using JSTL only. Is this possible?
I know how to retrieve the key value pairs, but I haven't found a way to set them.
Any help would be appreciated.
Example of retrieving HashMap key/value pairs using JSTL:
<c:forEach var="hash" items="${myHashMap}">
<c:out value="${hash.key}" />
<c:out value="${hash.value}" />
...
You can use the <c:set>.
<c:set target="${myHashMap}" property="key" value="value"/>
I wouldn't use JSTL to do that, but straight-up JSP will get it done...
<%
myHashMap.put("hello", "world");
%>

Categories