开发者

why EL functions in jsp must be declared as static?

开发者 https://www.devze.com 2023-04-09 18:49 出处:网络
I am reading some JSP text regarding EL user-defined functions, and the aut开发者_开发技巧hor said these kinds of functions must be declared static and gave no other explanation. I have tried to decla

I am reading some JSP text regarding EL user-defined functions, and the aut开发者_开发技巧hor said these kinds of functions must be declared static and gave no other explanation. I have tried to declare non-static functions and got a org.apache.jasper.JasperException: java.lang.NullPointerException.....

Can any one elaborate on that, please?


If they were not static, the runtime would be in charge of creating instances of the classes containing the functions. Resulting in state management on those objects - which in fact means you should have written a custom tag instead. You should treat EL functions as helpers only, in most cases you will want to create custom tags.


If those functions were not static, you would need some instance to call those methods on.

This is what latest version of Expression Language (from JSP 2.1) allows you to do. It can call methods (non-static functions):

${bean.doSomethingGreat('with arguments')}

(Original EL allowed you to call getters only, using ${bean.property} syntax).


Short answer: because the JavaServer Pages Specification, JSP.2.10 Functions said that:

Functions are mapped to public static methods in Java classes.

Two tips why it has to be static:

  • for historical reasons,

  • for performance reasons.

Today it's not a big deal to create a new object instance with a no-arg constructor then call the function method and let the garbage collector to get rid of the instance. If you are using the function in a big loop it could hurt but usually it's not a problem.

The instance methods would fit better with the test-driven world since it's easier to mock in tests than static methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号