I’m migrating an old application from JSP 1.1 to JSP 2.1, and trying to do everything without scriptlets. I have a JavaBean that I create, populate and insert into the page scope via a CustomTag. This JavaBean exposes some methods that transform data, generate HTML snippets, etc, based on it’s instance variables.
When I need to access a property in the JavaBean I use:
${mybean.property}
But since JSP 2.1/EL 2.1 don’t support calling methods on your beans (this requires JSP 2.2/EL 2.2), I’m trying to determine the best way to expose such utility methods to my JSP pages without resorting to scriptlets.
Here is an example of the methods on the JavaBean that I need to access:
public String getThumbColor() {
String tbgcolor = "#FF0000";
if (this.getJavaBuildTotal() > 0 &&
this.getJavaBuildBroke() == 0 &&
this.getCeeBuildBroke() == 0 &&
this.getJavaBuildInvalid() == 0 &&
!this.hasBuildException()) {
tbgcolor = "#00FF00";
}
else if (this.getJavaBuildTotal() == 0 && this.getCeeBuildTotal() == 0) {
tbgcolor = "#f7f814";
}
return tbgcolor;
}
It feels like converting this (and the 10 or so other methods like it) entirely to JSTL in the JSP would be muddying up my JSP page.
Since I’m already doing a large refactoring, I don’t mind drastic changes; yet I can’t think of anyway to eliminate my need of certain methods that use conditionals for deciding on return values, generate small HTML snippets, etc.
Have a look at JSTL. It offers at least a basic set of core tags to control the flow in the page. Use this instead of
if/else/switchwhatever in scriptlets. It also offers several utility methods in the functions taglib. BasicStringoperations such as substring and so on are offered by this. You could also homegrow custom EL functions yourself which can callpublic staticmethods with arguments.See also:
Update as per the information in the comment
You could add getters for those variables and use this in
<c:if>or whatever.You could even wrap this in a boolean getter in the bean if those values are for example constants.
which you use as follows:
There are lot of ways depending on the concrete functional requirement, which is still vague in your question.
See also:
Update 2: as per the new example in your question, presentation specifics should go in the view (JSP). The bgcolor is part of the presentation. I’d suggest to replace this by an enum.
And declare the color in the view
Or, better, make a CSS class of it
with in a style(sheet)