在JSP EL中使用接口默认方法时出现“类型上未找到属性”错误

24

请考虑以下接口:

public interface I {
    default String getProperty() {
        return "...";
    }
}

和只是重复使用默认实现的实现类:

public final class C implements I {
    // empty
}

每当在 JSP EL 脚本上下文中使用 C 的实例时:

<jsp:useBean id = "c" class = "com.example.C" scope = "request"/>
${c.property}

我收到一个PropertyNotFoundException的异常:

javax.el.PropertyNotFoundException: Property 'property' not found on type com.example.C
    javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:268)
    javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:221)
    javax.el.BeanELResolver.property(BeanELResolver.java:355)
    javax.el.BeanELResolver.getValue(BeanELResolver.java:95)
    org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110)
    org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:943)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:225)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我最初的想法是Tomcat 6.0因为Java 1.8的特性太旧了,但我很惊讶地发现Tomcat 8.0也受到影响。当然,我可以通过显式调用默认实现来解决这个问题:

    @Override
    public String getProperty() {
        return I.super.getProperty();
    }

-- 但是为什么默认方法对Tomcat可能会有问题呢?

更新: 进一步的测试表明默认属性找不到,而默认方法可以找到,因此另一个解决方法(适用于Tomcat 7+)是:

<jsp:useBean id = "c" class = "com.example.C" scope = "request"/>
<%-- ${c.property} --%>
${c.getProperty()}

1
我猜反射在接口的默认方法上不起作用?我对答案非常感兴趣 :) - Gaël J
你尝试过添加注解 @FunctionalInterface 吗? - rickz
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Bass
关于使用 getter 方法的非常有用的提示。至少在 OpenLiberty 的 22 版本中也适用。 - dbreaux
2个回答

9
您可以通过创建一个自定义的ELResolver实现来解决这个问题,该实现可以处理默认方法。我在这里制作的实现是扩展了SimpleSpringBeanELResolver。这是Spring的ELResolver实现,但是同样的想法应该也适用于非Spring环境。
此类会查找bean属性签名,这些签名在bean的接口上进行了定义,并尝试使用它们。如果在接口上没有找到bean prop签名,则继续将其发送到默认行为链中。
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.el.SimpleSpringBeanELResolver;

import javax.el.ELContext;
import javax.el.ELException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Resolves bean properties defined as default interface methods for the ELResolver.
 * Retains default SimpleSpringBeanELResolver for anything which isn't a default method.
 *
 * Created by nstuart on 12/2/2016.
 */
public class DefaultMethodELResolver extends SimpleSpringBeanELResolver {
    /**
     * @param beanFactory the Spring BeanFactory to delegate to
     */
    public DefaultMethodELResolver(BeanFactory beanFactory) {
        super(beanFactory);
    }

    @Override
    public Object getValue(ELContext elContext, Object base, Object property) throws ELException {

        if(base != null && property != null) {
            String propStr = property.toString();
            if(propStr != null) {
                Optional<Object> ret = attemptDefaultMethodInvoke(base, propStr);
                if (ret != null) {
                    // notify the ELContext that our prop was resolved and return it.
                    elContext.setPropertyResolved(true);
                    return ret.get();
                }
            }
        }

        // delegate to super
        return super.getValue(elContext, base, property);
    }

    /**
     * Attempts to find the given bean property on our base object which is defined as a default method on an interface.
     * @param base base object to look on
     * @param property property name to look for (bean name)
     * @return null if no property could be located, Optional of bean value if found.
     */
    private Optional<Object> attemptDefaultMethodInvoke(Object base, String property) {
        try {
            // look through interfaces and try to find the method
            for(Class<?> intf : base.getClass().getInterfaces()) {
                // find property descriptor for interface which matches our property
                Optional<PropertyDescriptor> desc = Stream.of(PropertyUtils.getPropertyDescriptors(intf))
                        .filter(d->d.getName().equals(property))
                        .findFirst();

                // ONLY handle default methods, if its not default we dont handle it
                if(desc.isPresent() && desc.get().getReadMethod() != null && desc.get().getReadMethod().isDefault()) {
                    // found read method, invoke it on our object.
                    return Optional.ofNullable(desc.get().getReadMethod().invoke(base));
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException("Unable to access default method using reflection", e);
        }

        // no value found, return null
        return null;
    }

}

接下来,您需要在应用程序的某个地方注册您的ELResolver。在我的案例中,我使用Spring的Java配置,因此我有以下内容:

@Configuration
...
public class SpringConfig extends WebMvcConfigurationSupport {
    ...
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        ...
        // add our default method resolver to our ELResolver list.
        JspApplicationContext jspContext = JspFactory.getDefaultFactory().getJspApplicationContext(getServletContext());
        jspContext.addELResolver(new DefaultMethodELResolver(getApplicationContext()));
    }
}

我不确定是否适合在那里添加我们的解析器,但它确实可以正常工作。您还可以在javax.servlet.ServletContextListener.contextInitialized期间加载ELResolver

这是参考ELResolverhttp://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html


我还没有尝试过这个,但如果默认方法被覆盖,这个解析器会返回覆盖后的值还是默认值?我希望它返回被覆盖的值。 - battmanz
@battmanz 我猜它应该返回被覆盖的值。但是我没有快速测试的方法。如果不是这样,那么您可以随时更改属性解析器的行为。 - ug_
1
如果默认方法属于父类实现的接口,即BaseClass实现了InterfaceWithDefaultMethodChildClass继承自BaseClass,则在ChildClass类的对象上找不到此属性。您应该将base.getClass().getInterfaces()替换为ClassUtils.getAllInterfaces(base) - izogfif
如果被调用的方法返回null,则也无法正常工作-将return ret.get();替换为return ret.orElse(null);以解决此问题。 - Gareth

0

Spring 5 移除了 SimpleSpringBeanELResolver,因此上面的答案不再适用,但事实证明,基类实际上并没有做任何事情。下面是 Spring 5 版本,修复了上面评论中讨论的问题(使用 XML 配置)

public class DefaultMethodELResolver extends ELResolver {

    @Override
    public Object getValue(ELContext elContext, Object base, Object property) throws ELException {

        if (base != null && property != null) {
            String propStr = property.toString();
            if(propStr != null) {
                Optional<Object> ret = attemptDefaultMethodInvoke(base, propStr);
                if (ret != null) {
                    // notify the ELContext that our prop was resolved and return it.
                    elContext.setPropertyResolved(true);
                    return ret.orElse(null);
                }
            }
        }

        return null;
    }

    @Override
    public Class<?> getType(ELContext elContext, Object o, Object o1) {
        return null;
    }

    @Override
    public void setValue(ELContext elContext, Object o, Object o1, Object o2) {

    }

    @Override
    public boolean isReadOnly(ELContext elContext, Object o, Object o1) {
        return false;
    }

    @Override
    public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext elContext, Object o) {
        return null;
    }

    @Override
    public Class<?> getCommonPropertyType(ELContext elContext, Object o) {
        return Object.class;
    }

    /**
     * Attempts to find the given bean property on our base object which is defined as a default method on an interface.
     * @param base base object to look on
     * @param property property name to look for (bean name)
     * @return null if no property could be located, Optional of bean value if found.
     */
    private Optional<Object> attemptDefaultMethodInvoke(Object base, String property) {
        try {
            // look through interfaces and try to find the method
            for(Class<?> intf : ClassUtils.getAllInterfaces(base.getClass())) {
                // find property descriptor for interface which matches our property
                Optional<PropertyDescriptor> desc = Stream.of(PropertyUtils.getPropertyDescriptors(intf))
                        .filter(d->d.getName().equals(property))
                        .findFirst();

                // ONLY handle default methods, if its not default we dont handle it
                if(desc.isPresent() && desc.get().getReadMethod() != null && desc.get().getReadMethod().isDefault()) {
                    // found read method, invoke it on our object.
                    return Optional.ofNullable(desc.get().getReadMethod().invoke(base));
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException("Unable to access default method using reflection", e);
        }

        // no value found, return null
        return null;
    }

    public static class CustomResolverListener implements ServletContextListener {

        public void contextInitialized(ServletContextEvent event) {
            var jspContext =  JspFactory.getDefaultFactory().getJspApplicationContext(event.getServletContext());
            jspContext.addELResolver(new DefaultMethodELResolver());
        }

        public void contextDestroyed(ServletContextEvent event) {
        }
    }
}

然后在web.xml中

<listener>
    <listener-class>DefaultMethodELResolver$CustomResolverListener</listener-class>
</listener>

1
请参见 https://dev59.com/gFTTa4cB1Zd3GeqPr2FD - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接