Announcement Announcement Module
No announcement yet.
Getting objects from model Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Getting objects from model

    I have a JSP view which is passed a model consisting of several business objects. I have logic defined within my business objects and can access them through "is" methods, ie: isClosed() : boolean.

    How do I obtain these objects from the model so that I can then perform a test of the object's state? For example, in my controller I create a Map consisting of an object Car and this is passed to my JSTL view via the ModelAndView object. I need to display a link in my view only if Car.isRunning() is true.

    I've tried <c:if test="${}">...</c:if> but that didn't work. I'm new to JSP and JSTL programming, so I don't know if this is a Spring or a JSTL question.


  • #2
    I think the problem may be in the "model" prefix in your variable path. Where did that come from? Remember the model map is a set of name=value pairs. Before a jsp page is rendered, the name=value pairs are injected as attributes in request scope. So in your jsp page, you simply access each request attribute by name; for example:

       &#91;in controller code, prepping the model content for the view&#93;
         modelMap.put&#40;"myCar", new Car&#40;"Grand Marquis"&#41;&#41;;
       &#91;in jsp page&#93;
        <c&#58;if test="$&#123;myCar.isRunning&#40;&#41;&#125;>...</c&#58;if>

    Yes, I really do drive a Grand Marquis ;-)


    • #3
      Hi Kevin!

      The "model" came from the name of the Map when I was constructing the ModelAndView object: return new ModelAndView("viewPage", "model", model);

      I tried both <c:if test="${myCar.isRunning()}"> and <c:if test="${model.myCar.isRunning()}"> and I receive a similar ServletException each time: The function isRunning must be used with a prefix when a default namespace is not specified.

      I've tried to Google the error message, but I've come up with dead ends. Just to be sure, this is how I am creating my model and returning it:
      Map model = new HashMap&#40;&#41;;
      model.put&#40;"myCar", new Car&#40;"Grand Marquis"&#41;&#41;;
      return new ModelAndView&#40;"myView", "model", model&#41;;
      Thanks again!


      • #4
        JSTL doesn't support calling methods explicitly. However, you should be able to access getters and boolean getters (i.e. isProperty()). Just remove the get/is:

        <c:if test="${myCar.running}">


        • #5
          Thanks Matt I didn't even seen that ;-) smv that definitely sounds like the other half of your problem!


          • #6
            Yes! That worked perfectly! Thank you both for helping me on this issue. I need to read more about JSTL as I thought it only worked on "get" accessors.