How to display my application's errors in JSF?

后端 未结 8 1545
栀梦
栀梦 2020-11-29 18:10

In my JSF/Facelets app, here\'s a simplified version of part of my form:


  

        
8条回答
  •  没有蜡笔的小新
    2020-11-29 18:40

    FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.

    So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.

    
      
        
        
      
    
    

    Managed bean logic:

    /** Must be request scope for binding */
    public class ShowMessageAction {
    
        private UIComponent mybutton;
    
        private boolean isOK = false;
    
        public String validatePassword() {
            if (isOK) {
                return "ok";
            }
            else {
                // invalid
                FacesMessage message = new FacesMessage("Invalid password length");
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(mybutton.getClientId(context), message);
            }
            return null;
        }
    
        public void setMybutton(UIComponent mybutton) {
            this.mybutton = mybutton;
        }
    
        public UIComponent getMybutton() {
            return mybutton;
        }
    }
    

提交回复
热议问题