带有转换器的 JSF selectManyListBox 不起作用

Posted

技术标签:

【中文标题】带有转换器的 JSF selectManyListBox 不起作用【英文标题】:JSF selectManyListBox with converter not working 【发布时间】:2014-01-01 22:36:16 【问题描述】:

直截了当,我得到 ClassCastException: java.lang.String cannot be cast com.jsf.domain.Owner 我认为转换器有问题,但我不知道它在哪里。

html

<h:selectManyListbox value="#myBean.target" converter="#myConverter">
    <f:selectItems value="#myBean.source" var="c" itemValue="#c"    itemLabel="#c.name #c.surname"/>
</h:selectManyListbox>
<h:commandButton value="Ok" action="#myBean.add()"/>

Bean 只剩下最重要的部分:

@SessionScoped
@Named("myBean")
public class MyFormBean implements Serializable 

    //Car has manytomany relationship with the owner
    private Car car = new Car();    
    private List<Owner> target; 

    @Inject
    OwnerManager om;    
    @Inject
    CarManager mm;

    public String add()
        mm.addOwners(car.getId(), target);  
        retur null;
    

    public List<Owner> getSource()
        om.getAllOwners();
       

    public List<Owner> getTarget()
        return target;  
    

    public void setTarget(List<Owner> target)
        this.target = target;
    

这是我的转换器:

@FacesConverter("myConverter")
public class myConverter implements Converter 

    @Inject
    CarManger mm;

    @Override Object getAsObject(FacesContext context, UIComponent component, String value)
        if(value == null)
            return null;
        
        return mm.getEntityManager.find(Owner.class, LongValueOf(value));
    

    @Override String getAsString(FacesContext context, UIComponent component, Object value)
        if(value == null)
            return null;
        
        if(value instanceof Car)
            return String.valueOf(((Owner) value).getId());
        
        return null;
    

还有一个问题,希望我不会被告知要为此单独发帖。我是否正确理解,当源是一个复杂对象时,首先在检索它时调用 getAsString 方法,然后在将它返回到源时调用 getAsObject ?感谢所有帮助。

编辑:

    [2014-01-01T22:03:34.266+0100] [glassfish 4.0] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=18 _ThreadName=http-listener-1(1)] [timeMillis: 1388610214266] [levelValue: 900] [[
      StandardWrapperValve[FacesServlet]: Servlet.service() for servlet FacesServlet threw exception
    java.lang.ClassCastException: java.lang.String cannot be cast to com.jsf.domain.Owner
        at com.jsf.domain.CarManager.addOwnerToCar(CarManager.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
        at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
        at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
        at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
        at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
        at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
        at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
        at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
        at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
        at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
        at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
        at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
        at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
        at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
        at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
        at com.sun.proxy.$Proxy386.addOwnerToCar(Unknown Source)
        at com.jsf.service.__EJB31_Generated__CarManager__Intf____Bean__.addOwnerToCar(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:396)
        at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:108)
        at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
        at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:63)
        at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:101)
        at com.jsf.service.CarManager$Proxy$_$$_Weld$EnterpriseProxy$.addOwnerToCar(Unknown Source)
        at com.jsf.web.MyBean.addCar(MyBean.java:61)
        at com.jsf.web.MyBean$Proxy$_$$_WeldClientProxy.addCar(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
        at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
        at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
        at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
        at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
        at javax.faces.component.UICommand.broadcast(UICommand.java:315)
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        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.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
        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:724)
    ]]

addOwners 方法

  @PersistenceContext
  EntityManager em;

  public void addOwners(Long carId, List<Owner> owners)
      Car car = em.find(Car.class, carId);
      for(Owner o : owners)
          car.getOwners().add(o);
      
  

【问题讨论】:

您能提供更多细节吗?异常的堆栈跟踪和上面代码中的标记相关行 我编辑了我的帖子。这是出现异常的相关行mm.addOwners(car.getId(), target); stacktrace 显示CarManager 中的方法引发了异常。您确定这与转换器有关吗?看起来传递的是 String 而不是 Owner 对象,但在将值传递到后端的那一刻,使用了 getAsObject 方法,该方法确实返回了 Owner 对象...... 我添加了方法,我对 JSF 很陌生,所以我可能错了,但是为什么将 List 目标传递给这个方法会导致这个特殊的异常? @unwichtich 嘿,原来问题是我在转换器属性中使用了表达式。 【参考方案1】:

第一个问题是 Converter 不能从它的 getAsString 方法返回 null。来自the javadoc:

返回:如果值为null,则返回零长度字符串,否则为转换结果

如果您违反该合同并返回 null,预计事情会破裂。 (说真的,我已经看到它在 Mojarra 中引起了一些非常奇怪的行为。)

第二个问题是converter="#myConverter" 是一个表达式,它需要一个名为 myConverter 的作用域变量,但没有这样的变量。 @FacesConverter("myConverter") 注释不会将变量放入任何范围,因此它不会以任何方式使 #myConverter 成为有效表达式。相反,使用注释注册在 JSF 应用程序中的转换器类下 converter ID 作为注释的 value 参数给出,使用 addConverter(String, String) method of javax.faces.application.Application。

删除converter= 属性,并在 中添加一个子元素,如下所示:

<f:converter converterId="myConverter"/>

【讨论】:

谢谢,我现在才注意到我在转换器中做了一个表达式。当我将它更改为简单的 myConverter 时,它突然起作用了,我会记住不要在 getAsString 中返回 null。再次感谢您,祝您有美好的一天!

以上是关于带有转换器的 JSF selectManyListBox 不起作用的主要内容,如果未能解决你的问题,请参考以下文章

将带有 Ajax4jsf 1.x 的 JSF 1.1 迁移到 JSF 2

了解带有和不带有重定向的 JSF 生命周期阶段

当 JSF 2 的视图中存在元数据转换器时,为啥 JSTL-JSF2 不能正常工作

带有 JSF 项目的组件库

JSF - 带有“时间”值的范围滑块

带有 Eclipse 和 Tomcat 的 JSF 2.0 教程 [关闭]