"Свойство не найдено для типа" при использовании методов интерфейса по умолчанию в JSP EL
Рассмотрим следующий интерфейс:
public interface I {
default String getProperty() {
return "...";
}
}
и реализующий класс, который просто повторно использует реализацию по умолчанию:
public final class C implements I {
// empty
}
Всякий раз, когда экземпляр C
используется в контексте сценариев JSP EL:
<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()}
2 ответа
Вы можете обойти это, создав пользовательский ELResolver
реализация, которая обрабатывает методы по умолчанию. Реализация, которую я сделал здесь, расширяет SimpleSpringBeanELResolver
, Это реализация Спрингс ELResolver
но та же идея должна быть такой же без весны.
Этот класс ищет сигнатуры свойств бина, определенные на интерфейсах бина, и пытается их использовать. Если в интерфейсе не было обнаружено никакой подписи бобов, оно продолжает отправлять его по цепочке поведения по умолчанию.
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
в вашем приложении где-то. В моем случае я использую Java-конфигурацию Spring, поэтому у меня есть следующее:
@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()));
}
}
Я не уверен на 100%, подходит ли это место для добавления нашего резольвера, но он работает просто отлично. Вы также можете загрузить ELResolver во время javax.servlet.ServletContextListener.contextInitialized
Здесь ELResolver
в ссылке: http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html
Если кому-то еще интересно, как использовать приведенный выше ответ с конфигурацией XML, вы можете добавить приведенный ниже ответ в качестве внутреннего класса ответа, приведенного выше:
public static class CustomResolverListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
var jspContext = JspFactory.getDefaultFactory().getJspApplicationContext(event.getServletContext());
var appContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
jspContext.addELResolver(new DefaultMethodELResolver(appContext));
}
public void contextDestroyed(ServletContextEvent event) {
}
}
а затем в web.xml
<listener>
<listener-class>DefaultMethodELResolver$CustomResolverListener</listener-class>
</listener>