开发者

Spring MVC 3.0 Model attribute is unexpectedly converted from List to String in JSP

开发者 https://www.devze.com 2023-02-17 14:28 出处:网络
Using Spring MVC 3.0, from my controller when I add a List object as an attribute to my model, it gets converted to a String in my JSP template.

Using Spring MVC 3.0, from my controller when I add a List object as an attribute to my model, it gets converted to a String in my JSP template.

Here's a simplified version of my controller:

@Controller
@RequestMapping("/reservationQuery")
public class ReservationQueryController {

    @RequestMapping(method = RequestMethod.GET)
    public void setupForm(Model model) {
        List<Reservation> reservations = java.util.Collections.emptyList();
        model.addAttribute("reservations", reservations);
    }
}

A breakpoint on the last line confirms that the reservations variable is an empty List. Here is reservationQuery.jsp:

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

<c:forEach items="${reservations}" var="reservation">
    ...
</c:forEach>

A breakpoint at the beginning of the c:forEach loop shows that the List, reservations, was converted to the String representation of an empty list, "[]". Why?

Just a开发者_运维知识库s strange is the fact that the page attempts an iteration, even though a string is not iterable (well maybe it is by character, but that's not what's happening). Even if I set reservations to an empty string it also tries to do an iteration. Of course, it throws an exception within the loop when I try to access a property of reservation that does not exist. In both cases, reservation was set to a string with the value "{reservations}". WTF?

  1. Why is the reservations attribute converted from a List to a String?
  2. And why does the JSP do an iteration of a string, setting the forEach variable to the literal string "{reservations}"?


At some point I changed this mistake:

<c:forEach items="reservations" var="reservation">

To this:

<c:forEach items="${reservations}" var="reservation">

But my IDE was not saving changes to my JSP file until I restarted my computer. After restarting and fixing the line, I was fine. I had some pending Windows updates and I wonder if that had anything to do with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消