If-then-else inside a JSP expression?

删除回忆录丶 提交于 2019-12-31 13:01:13

问题


Can you do an if-then-else statement inside a JSP expression?

EDIT : Specifically I was looking for a JSP solution, not a JSTL solution. But some JSTL solutions below are highly rated and are very welcome. Just please do not vote me down for a duplicate question because one has already been asked about JSTL.


回答1:


In JSP EL 2.0, you can do that using the ternary operator. For instance:

<option value="1" ${param.number == 1 ? 'selected' : ''}>First option</option>

What it does is it checks JSP's param's number variable. If it's 1, then selected is substituted. otherwise, nothing.




回答2:


If you are using JSTL you can do choose-when-otherwise.

<c:choose>
  <c:when test="condition"></c:when>
  <c:when test="condition2"></c:when>
  <c:otherwise></c:otherwise>
</c:choose>

For more information on JSTL try here.




回答3:


You can wrap your html code with jsp tags like this:

<% if (condition) { %>
<div>Condition is true!</div>
<% } else { %>
<div>Condition is false</div>
<% } %>



回答4:


there is a different way I use because Eclipse keep telling me that it can't resolve a variable which is coming from the servlet while executing which is below (PS: Am new to JSP):

${if(var != null)"text to print"}
${if(var != null)var}  to print a variable 
${if(var != null)"text to print"}

the result will be like

text to print <var value here> text to print



来源:https://stackoverflow.com/questions/9008011/if-then-else-inside-a-jsp-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!