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

两盒软妹~` 提交于 2019-11-29 10:21:46

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);
            }
        }
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!