2
<c:set var="product" value="#{productDAO.findByCode('code')}"  />
#{product.name}
#{product.name}

I would like to retrieve an object from the DB and store into a variable once. However, I find the call to the DB is made everytime I access product. In the example above there are two calls to the DB.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
DD.
  • 21,498
  • 52
  • 157
  • 246
  • 1
    You should not be invoking Model from your View. – Ravi K Thapliyal Apr 29 '13 at 21:04
  • 1
    @Ravi Thats not very helpful. – DD. Apr 29 '13 at 21:14
  • Any reason why the Model can't fire DAO code and set the bean as View scoped? I'm sure `#{product.name}` would work correctly then. – Ravi K Thapliyal Apr 29 '13 at 21:17
  • 1
    Related: http://stackoverflow.com/q/16268940/1065197. By the way, in JSF, you don't have to set a variable using JSTL + EL, this will just lead to other problems since `#{product.name}` can't be set to anything since it defines a deferred evaluation expression. Refer to [StackOverflow EL wiki](http://stackoverflow.com/tags/el/info) and [JSTL in JSF2 Facelets… makes sense?](http://stackoverflow.com/q/3342984/1065197) – Luiggi Mendoza Apr 30 '13 at 04:38
  • You shuold understand JSF MVC structure well. http://stackoverflow.com/questions/10111387/understanding-jsf-as-a-mvc-framework – erencan Apr 30 '13 at 07:54

1 Answers1

8

You need to explicitly specify the scope.

<c:set var="product" value="#{productDAO.findByCode('code')}" scope="request" />

The proper approach, however, is to create and use a request scoped managed bean and put this logic in its @PostConstruct.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Without the `scope` attr `product` goes into `Page` scope. How does setting the `scope` to `request` change the current behaviour? Please help understand. – Ravi K Thapliyal May 01 '13 at 14:49
  • @Ravi: uh, it goes into request scope. – BalusC May 01 '13 at 15:11
  • Yes, I understand that but how does it prevent the OP's problem? `"I find the call to the DB is made everytime I access product."` – Ravi K Thapliyal May 01 '13 at 15:36
  • 3
    @Ravi: it's then evaluated once per request instead. Note that the scopeless one represents the `none` scope and then the `` acts merely as an "alias". The underlying EL expression is then still evaluated everytime the variable is referenced. Run a debugger to see it yourself. – BalusC May 01 '13 at 15:48
  • 1
    DD: I think @BalusC answer solves your problem (it solved mine), if so then it would be good if you could accept the answer .. some housekeeping please .. – hagrawal7777 Aug 03 '18 at 11:09