JSF 2.0 @ManagedProperty返回null值

时间:2013-05-24 11:33:29

标签: jsf-2

通过定义managedproperty将一个托管bean注入另一个托管bean会有一些麻烦。但该属性为null。任何人都可以告诉我,为什么我的财产是空的? UserLoginBean.java

    @RequestScoped
public class UserLoginBean extends AbstractMB implements Serializable{

    private static final long serialVersionUID = 1L;
    private String username;
        private String password;
//getter and setter
        public void login() throws ServletException, IOException{
    try
    {
      ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); 
      HttpServletRequest request = ((HttpServletRequest)context.getRequest());

      ServletResponse resposnse = ((ServletResponse)context.getResponse());
      RequestDispatcher dispatcher = request.getRequestDispatcher("/j_spring_security_check");
      dispatcher.forward(request, resposnse);
      FacesContext.getCurrentInstance().responseComplete();
     }
    catch (Exception ex) {
        ex.printStackTrace();
        displayErrorMessageToUser("Login or Password Failed");
    }

ReclamationMB.java

@RequestScoped
public class ReclamationMB extends AbstractMB implements Serializable {
...
@ManagedProperty("#{loginBean}")
    private UserLoginBean userLogin;
/getter and setter

但是在.xhtml中它不是null,它返回用户名:

<h:outputText value="#{loginBean.username}

1 个答案:

答案 0 :(得分:0)

ReclamationMB中的userLogin是null还是用户名为null?如果userLogin不为null,则注入工作正常,但是bean是Requestscoped新创建的。 您可以将UserLoginBean放入Viewscope以防止重新创建bean:

@ViewScoped
 public class UserLoginBean extends AbstractMB implements Serializable{...}

或者您可以通过提供PostConstruct方法在ReclamationsMB中手动填充userLogin所需的数据

@RequestScoped
 public class ReclamationMB extends AbstractMB implements Serializable {
 ...
 @ManagedProperty("#{loginBean}")
 private UserLoginBean userLogin; //getter and setter

 @PostConstruct
 public void init() {
   //Call Bean methods or set variables manually
   userLogin.setUsername(...);
 }