简体   繁体   中英

struts2 switch statement

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 style attribute.

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 var value 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.

<p class="${answerClass}">The quick brown fox jumped over the lazy brown dog.</p>

CSS:

under: {
  color: red;
}

equal: {
  color: blue;
}

greater: {
  color: green;
}

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.

It's better use the logical part in the action. So evaluate the color value in a method.

But if you need to do this in JSP you can do also this:

<p style="color: 
   <s:if test="%{var < 50}">
      red
   </s:if>
   <s:elseif test="%{var == 50}">
      blue
   </s:elseif>
   <s:elseif test="%{var > 50}">
      pink
   </s:elseif>
;" >The quick brown fox jumped over the lazy brown dog.</p>

Just a way to avoid repetition of HTML. (DRY principle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM