struts2三元表达式
做项目已经好几次遇到在Struts2标签中使用三元表达式,每次都要试几次才能得到正确的结果,今天记录在这里,避免再走弯路,下面是正确的写法。
- <input <s:property value='%{#examQuestion.question.answer=="A"?"checked":""}'/> type="radio" name="answer" value='A'>A</input>
- <input <s:property value='%{#examQuestion.question.answer=="B"?"checked":""}'/> type='radio' name="answer" value='B'>B</input>
- <input <s:property value='%{#examQuestion.question.answer=="C"?"checked":""}'/> type="radio" name="answer" value='C'>C</input>
- <input <s:property value='%{#examQuestion.question.answer=="D"?"checked":""}'/> type='radio' name="answer" value='D'>D</input>
单选款中通过三元表达式判断哪个选项被选中,重点是"=="右边的写法,如果比较的是字符串则一定要用双引号,即将双引号写在花括号内部,将单引号写在外部,下面是错误的写法:
- <input <s:property value="%{#examQuestion.question.answer=='A'?'checked':''}"/> type="radio" name="answer" value='A'>A</input>
- <input <s:property value="%{#examQuestion.question.answer=='B'?'checked':''}"/> type='radio' name="answer" value='B'>B</input>
- <input <s:property value="%{#examQuestion.question.answer=='C'?'checked':''}"/> type="radio" name="answer" value='C'>C</input>
- <input <s:property value="%{#examQuestion.question.answer=='D'?'checked':''}"/> type='radio' name="answer" value='D'>D</input>
如果三元表达式比较的是数字,则"=="右边不能添加单引号或者双引号,下面两种都是正确的写法:
- <input <s:property value='%{1==1?"checked":""}'/> type="radio" name="answer" value='A'>A</input>
- <input <s:property value="%{1==1?'checked':''}"/> type="radio" name="answer" value='A'>A</input>