Why JSF2 @ViewScoped not working?

javax.faces.bean.ViewScoped said as long as you stay on the same view/page, the backing bean should be the same. This is useful if you want to retain some state of the backing bean, whilst avoid caching too much stuff in the session. I think it's quite useful in the searching/pagination screens.

 

However, my previous testing showed that it's not as expected in that it created new instances for different request for the searchStudent screen.

 

A recent reading solved this myth.

 

The problem is that although the search method "findByName" returned the same page "student/studentSearch.xhtml", JSF treated it as different view. To make it "stays on the same view", the search method in the backing bean should return null or nothing. Here's how it should look like:

@ManagedBean(name="ss")
@ViewScoped
public class StudentSearch implements Serializable {

  ...
  public void findByName() {
    log.debug("searching student for name: " + this.nameFilter);
    searchResultList = dao.find(this.nameFilter, maxRows);
  }

  or

  public String findByName() {
    log.debug("searching student for name: " + this.nameFilter);
    searchResultList = dao.find(this.nameFilter, maxRows);
    return null;
  }
  ...

}

If we code the search method like this, JSF would think it stays on the same view and javax.faces.bean.ViewScoped should be working as expected. This would enbable you replace the @SessionScoped backing bean, if you are concerned about caching too many objects in session.

 

This is working, but if you take a look at the server log, JSF2 actually still creates a new instance for you if you click column header to sort, or a page number to goto etc. But it manges to maintain the state for you, transparently.

 

If you really want to stick to the "same" instance, it looks like that you can configure one of these JSF properties in "web.xml". Use of "javax.faces.FULL_STATE_SAVING_VIEW_IDS" is recommended and you can define a comma separated list of pages/view for it.

<!-- it's said that this would incur performance cost
<context-param>
    <param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
    <param-value>false</param-value>
</context-param>
-->
	 
<context-param>
    <param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
    <param-value>/student/studentSearch.xhtml,/student/studentDetails.xhtml</param-value>
</context-param>

 

So lets sum it up here:

A @ViewScoped bean will live as long as you're submitting the form to the same view again and again. In other words, as long as when the action method(s) returns null or even void, the bean will be there in the next request. Once you navigate to a different view, then the bean will be trashed.

-- from: http://balusc.blogspot.co.nz/2010/06/benefits-and-pitfalls-of-viewscoped.html

你可能感兴趣的:(jsf2,@ViewScoped)