开发者

Why should EL functions be from Java methods with non-void return types?

开发者 https://www.devze.com 2023-03-23 21:33 出处:网络
I have a situation in which I think it is a good idea to use an EL function that is a void java method. This is a simple jsp to update a database of people\'s first and last name. So, there are two te

I have a situation in which I think it is a good idea to use an EL function that is a void java method. This is a simple jsp to update a database of people's first and last name. So, there are two text fields, name and password. The user enters them and clicks submit, and it forwards these with POST to another jsp. This jsp simply calls the EL function, let's call it "put" that takes two parameters and is derived from a java method putPerson(String, String) that gets a connection to the database and puts the first and last name in their proper places. Now, putPerson is void because all it does is put the strings in the database. So, is this bad programming practice, and if so, why? It seems to me to be a quick and elegant solution, and it works. The only problem is that you 开发者_如何学编程can't just call it by saying ${put(first, last)} because that prints out "<", for some reason, but that's easy enough to work around. So why do they recommend to not use EL functions with void return types?


Printing < would be coming from somewhere else, or is a bug in the EL parser. But either way, you should not do that in an EL function.

EL functions are meant to be utilities - for example .substring(), .join() (arrays), etc. And they are used while you are displaying the page and need some more complex presentation logic.

What you want to do is a typical story and it is done in a servlet (or any other action component, if you are using a framework).


The mechanism you need is older than EL - and it is called a scriptlet:

<%
    whatever.putPerson("John", "Smith");
%>

In early JSP another syntax was used to just print values (notice the equals sign):

<%=
    whatever.getVal();
%>

Because it was felt that it is easier to maintain code when there is a command / query separation, EL was introduced as a way to query model (= read properties of beans). Since scriptlets were available to cater for the rare cases when simply "running some code" would be necessary, adding such functionality to EL would have no sense: we would have two ways to achieve the very same thing and we would break the concept of EL expressions always having a value and a type.

So:

  • using EL for calling void methods is like... uhmpf... using import for running code: it makes no sense;
  • this is not a problem, since you can use the very mechanism that was made to call methods: a scriptlet.
0

精彩评论

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

关注公众号