3

编辑:我缩小了问题范围并在此处发布了相关问题。请检查一下!

我正在尝试使用动态代理来简化 HTML 表单处理。我正在使用 Google App Engine 上的 JSP 使用非常简单的 MVC 设置(没有花哨的框架)。我不断收到以下异常:

javax.el.PropertyNotFoundException: Could not find property testValue in class com.sun.proxy.$Proxy7
    at javax.el.BeanELResolver.toBeanProperty(BeanELResolver.java:430)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:290)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:231)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:123)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
    ...

好的,这里是代码。首先,我代理的接口:

public interface MyForm {
      public String getTestValue();
}

接下来,创建代理的代码:

// imports omitted

public final class Forms {

    private Forms() { }

    public static <T> T fromRequest(
            final Class<T> klass,
            final HttpServletRequest request) {

        Object proxy = Proxy.newProxyInstance(
                klass.getClassLoader(),
                new Class<?>[]{ klass },
                new InvocationHandler() {
                    @Override public Object invoke(
                            Object proxy,
                            Method method,
                            Object[] args) throws Throwable {

                        return "Will this be returned?";
                    }
                });
        return (T)proxy;
    }
}

接下来是“动作”类:

// imports omitted

public class MyAction extends Action {

    // Called by the controller, which forwards to the returned JSP
    public String perform(HttpServletRequest request) throws Exception {

        final MyForm form = Forms.fromRequest(MyForm.class, request);
        request.setAttribute("form", form);
        return "view.jsp";
    }
}

最后,JSP:

<html>
    <body>
        <div>${ form.testValue }</div>
    </body>
</html>

如您所见,我实际上还没有进行任何表单处理。首先,我只想用动态代理实现概念证明。如前所述,上面的代码不起作用。然而,令人困惑的是,如果我将请求属性设置为一个简单地转发到代理的匿名类,它确实有效!因此,以下更改修复了它:

request.setAttribute("form", new MyForm() {
    @Override getTestValue() { return form.getTestValue(); }
});

但是,必须匿名子类化接口类型违背了代理的目的。有人可以告诉我发生了什么吗?

4

0 回答 0