How to create JSF form with AJAX data validation

后端 未结 2 1694
抹茶落季
抹茶落季 2021-01-13 19:50

I\'m working on a JSF form prototype for inserting data into database table using AJAX data validation This is the JSF page:



        
2条回答
  •  清歌不尽
    2021-01-13 20:23

    You need to create a Validator.

    Kickoff example:

    @FacesValidator("sessionIdValidator")
    public class SessionIdValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            // ...
    
            if (yourDataService.existSessionId(value)) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Session ID is already in use, please choose another.", null));
            }
        }
    
    }
    

    Use it as follows:

    
        
        
                                                  
    
    
    

    Note that you should use a to show validation messages. You haven't any one in your view. Apply the same for all your other fields:

    
        
                                                  
    
    
    

    If you want to use @Resource or @EJB or @Inject in the validator, then replace the @FacesValidator annotation by @ManagedBean or (as you seem to use CDI for some reason) @Named:

    @Named
    public class SessionIdValidator implements Validator {
    
        @Resource
        private DataSource dataSource;
    
        @Inject
        private YourDataService yourDataService;
    
        // ...
    }
    

    and use it as follows instead

        
    

提交回复
热议问题