java.lang.IllegalStateException: java.lang.InstantiationException while implementing a custom tag handler in JSF

后端 未结 1 1817
小蘑菇
小蘑菇 2020-12-19 07:08

Given the following tag handler class.

public final class ViewParamValidationFailed extends TagHandler implements ComponentSystemEventListener
{
    private          


        
相关标签:
1条回答
  • 2020-12-19 07:26

    By default, JSF serializes the view state (the component tree state) for any <h:form> in the view (as <input type="hidden" name="javax.faces.ViewState">). This is restored during the restore view phase of the postback request on that form. The JSF view state covers among others the component system event listeners of the components in the tree.

    This line

    ((UIViewRoot) parent).subscribeToEvent(PostValidateEvent.class, this);
    

    adds one to the UIViewRoot component and this then needs to be serialized.

    You've 4 options:

    1. Let it implement Serializable.
    2. Let it implement Externalizable.
    3. Unsubscribe the listener when it's done with its job.
    4. Use SystemEventListener instead of ComponentSystemEventListener.

    In this particular case, as long as you don't need to support the nesting of the tag inside the individual <f:viewParam>, but only in <f:metadata>, then option 4 should suffice. Replace the ComponentSystemEventListener interface by SystemEventListener, implement the isListenerForSource() method to return true for UIViewRoot only, finally use UIViewRoot#subscribeToViewEvent() instead to subscribe the listener.

    public final class ViewParamValidationFailed extends TagHandler implements SystemEventListener {
        private final String redirect;
    
        public ViewParamValidationFailed(TagConfig config) {
            super(config);
            redirect = getRequiredAttribute("redirect").getValue();
        }
    
        @Override
        public void apply(FaceletContext context, UIComponent parent) throws IOException {
            if (parent instanceof UIViewRoot && !context.getFacesContext().isPostback()) {
                ((UIViewRoot) parent).subscribeToViewEvent(PostValidateEvent.class, this);
            }
        }
    
        @Override
        public boolean isListenerForSource(Object source) {
            return source instanceof UIViewRoot;
        }
    
        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            FacesContext context = FacesContext.getCurrentInstance();
    
            if (context.isValidationFailed()) {
                try {
                    ExternalContext externalContext = context.getExternalContext();
                    externalContext.redirect(externalContext.getRequestContextPath() + redirect);
                }
                catch (IOException e) {
                    throw new AbortProcessingException(e);
                }
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题