Does a solution to this problem exist in Struts2?
<s:if test="%{var < 50}">
<p style="color: red;">The quick brown fox jumped over the lazy brown dog.</p>
</s:if>
<s:elseif test="%{var == 50}">
<p style="color: blue;">The quick brown fox jumped over the lazy brown dog.</p>
</s:elseif>
<s:elseif test="%{var > 50}">
<p style="color: pink;">The quick brown fox jumped over the lazy brown dog.</p>
</s:elseif>
Ideally I would have liked to use a switch statement here, but that appears non-existent. Is there another suitable solution, instead of typing out the same line with minor changes?
Yes, set a variable, and refer to it in your
styleattribute.This has nothing to do with Struts 2 specifically, however; that’s common-sense refactoring.
I don’t know your usecase, but I’d prefer to see it taken a step further: the
varvalue must mean something to your application, like “under, equal, over” or something. Rather than tie the value directly to CSS properties, let the application-level semantics be all you worry about in the HTML. Use CSS more-appropriately (and more flexibly) to accomplish the same thing.CSS:
Note that I changed the colors, using pink and red for “opposite” ends of a scale strikes me as counter-intuitive, and not so great for those that have color blindness in that color range.
The logic for selecting the CSS class name could exist in the JSP, but IMO it’s easier to put it in the application’s Java code, where it can be tested and tweaked in a wider variety of ways than if it’s embedded in the view layer.