Every time I make an Ajax request in JSF2 I am get

2019-02-27 08:08发布

问题:

Hi I am getting a new session bean for every ajax request made to this Bean... Can any of you tell me why ?

...... imports ......
@Named(value = "userController")
@SessionScoped
public class UserController implements Serializable {

private User current;
private DataModel items = null;
@EJB
private br.com.cflex.itm.dataaccess.UserFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;

public UserController() {
}

public Collection<Project> getMyProjectList(){
    String login = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
    User u = ejbFacade.getUserFromLogin(login);
    return u.getProjectCollection();
}    

public User getSelected() {               
    if (current == null) {
        current = new User();
        selectedItemIndex = -1;
    }
    return current;
} 
....... rest of class ....

Every time I make this request I am getting a new of this SessionBean I for as far as I know I should be getting the same guy over and over again.

    <h:panelGrid columns="2" cellpadding="2">
      <h:form>
       <h:outputText value="#{bundle.FirstName}"/>                                
         <h:inputText id="name" value="#{userController.selected.name}">
          <f:ajax event="keyup" execute="name" render="out" />
<!--       <f:ajax event="keyup" render="out"/>-->
           </h:inputText>
           <p>
            <h:commandButton value="add"></h:commandButton>      
            <h:outputText id="out" value="#{userController.selected.name}"/>
           </p>
      </h:form>
    </h:panelGrid>

回答1:

That can happen if you accidently imported @SessionScoped from the javax.faces.bean package instead of the javax.enterprise.context package.

You're using @javax.inject.Named annotation, so you should import the scopes from the javax.enterprise.context package. The scopes from the javax.faces.bean package only works in combination with @javax.faces.bean.ManagedBean annotation.

A CDI bean without a valid scope will behave like @RequestScoped. A JSF bean without a valid scope will behave like @NoneScoped.