java.lang.IllegalStateException:在 JSF 中实现自定义标记处理程序时出现 java.lang.InstantiationException

Posted

技术标签:

【中文标题】java.lang.IllegalStateException:在 JSF 中实现自定义标记处理程序时出现 java.lang.InstantiationException【英文标题】:java.lang.IllegalStateException: java.lang.InstantiationException while implementing a custom tag handler in JSF 【发布时间】:2014-07-12 10:17:34 【问题描述】:

给定以下标签处理程序类。

public final class ViewParamValidationFailed extends TagHandler implements ComponentSystemEventListener

    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).subscribeToEvent(PostValidateEvent.class, this);
        
    

    @Override
    public void processEvent(ComponentSystemEvent 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);
            
        
    

标签处理程序仅用于在转换失败时重定向到页面。

这在 Xhtml 页面上使用如下。

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:my="http://example.com/ui"
      xmlns:f="http://xmlns.jcp.org/jsf/core">

    <h:head>
        <title>Test</title>
    </h:head>

    <h:body>
        <f:metadata>
            <f:viewParam name="id" required="true" value="#testManagedBean.id"/>
            <my:viewParamValidationFailed redirect="/public_resources/PageNotFound.jsf"/>
        </f:metadata>

        <h:form id="form" prependId="true">
            <p:commandButton value="Submit" actionListener="#testManagedBean.submitAction"/>
        </h:form>
    </h:body>
</html>

我们可以使用&lt;f:viewParam&gt; 有一个可选的转换器属性,就像converter="javax.faces.Long" 一样

实际上,有一个模板,其中&lt;f:metadata&gt; 包含在&lt;ui:define name="metaData"&gt; 中。

关联的 JSF 托管 bean:

@ManagedBean
@RequestScoped
public final class TestManagedBean

    private Long id; // Getter and setter.

    public TestManagedBean() 

    public void submitAction() 
        System.out.println("submitAction() called.");
    

当给定的&lt;p:commandButton&gt;被按下时,会抛出以下异常。

SEVERE:   java.lang.IllegalStateException: java.lang.InstantiationException: tags.ViewParamValidationFailed
    at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:153)
    at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.restoreState(UIComponent.java:2633)
    at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:165)
    at javax.faces.component.UIComponentBase.restoreAttachedState(UIComponentBase.java:1793)
    at javax.faces.component.UIComponentBase.restoreSystemEventListeners(UIComponentBase.java:1911)
    at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1607)
    at javax.faces.component.UIViewRoot.restoreState(UIViewRoot.java:1771)
    at com.sun.faces.application.view.FaceletPartialStateManagementStrategy$2.visit(FaceletPartialStateManagementStrategy.java:380)
    at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1690)
    at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.restoreView(FaceletPartialStateManagementStrategy.java:367)
    at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:138)
    at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:123)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:590)
    at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:150)
    at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
    at org.omnifaces.viewhandler.RestorableViewHandler.restoreView(RestorableViewHandler.java:66)
    at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:197)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.Abstractiostrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.InstantiationException: tags.ViewParamValidationFailed
    at java.lang.Class.newInstance0(Class.java:357)
    at java.lang.Class.newInstance(Class.java:325)
    at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:150)
    ... 54 more

这个标签处理程序应该只与&lt;f:viewParam&gt; 相关联,并且应该被完全跳过,例如,当回发时。

有什么解决办法吗?


关键:

apply()方法里面的条件检查中,

if (parent instanceof UIViewRoot && !context.getFacesContext().isPostback()) 
    System.out.println("Inside if");
    ((UIViewRoot) parent).subscribeToEvent(PostValidateEvent.class, this);

当给定的按钮被点击时,这个条件被评估为假,这是显而易见的。因此,应该没有任何问题。

令人惊讶的是,当if 语句中的唯一一行被删除时,异常消失了,如下所示。

if (parent instanceof UIViewRoot && !context.getFacesContext().isPostback()) 
    //Debug statements only.

在这种情况下,当按下给定的&lt;p:commandButton&gt; 时,尽管条件被评估为假,但它不会抛出上述异常。

从未见过这种情况:)

【问题讨论】:

【参考方案1】:

默认情况下,JSF 序列化视图中任何&lt;h:form&gt; 的视图状态(组件树状态)(如&lt;input type="hidden" name="javax.faces.ViewState"&gt;)。这是在该表单上的回发请求的恢复视图阶段恢复的。 JSF 视图状态包括树中组件的 component 系统事件侦听器。

这一行

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

将一个添加到UIViewRoot 组件,然后需要对其进行序列化。

您有 4 个选项:

    让它实现Serializable。 让它实现Externalizable。 在侦听器完成其工作后取消订阅它。 使用SystemEventListener 而不是ComponentSystemEventListener

在这种特殊情况下,只要您不需要支持将标签嵌套在单个 &lt;f:viewParam&gt; 中,而仅在 &lt;f:metadata&gt; 中,那么选项 4 就足够了。将ComponentSystemEventListener接口替换为SystemEventListener,实现isListenerForSource()方法只为UIViewRoot返回true,最后用UIViewRoot#subscribeToViewEvent()代替订阅监听器。

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


【讨论】:

以上是关于java.lang.IllegalStateException:在 JSF 中实现自定义标记处理程序时出现 java.lang.InstantiationException的主要内容,如果未能解决你的问题,请参考以下文章