Posted on 2010-07-28 16:13
BearRui(AK-47) 閱讀(4247)
評論(29) 編輯 收藏 所屬分類:
Java
相信很多使用jstl的朋友都抱怨過,為什么jstl只有<c:if 而沒有elseif、else。當需要判斷多個條件的時候,只能寫多個<c:if 或者使用<c:choose。
雖然struts有elseif 和 else標簽,不過看著就跟多個<c:if 沒什么2樣,使用如下:
<s:if test="">
1
</s:if>
<s:elseif test="">
2
</s:elseif>
<s:else>
3
</s:else>
下面是本人實現(xiàn)的if elseif else。先看看使用代碼:
<g:if test="">
1
<g:elseif test="" />
2
<g:else />
3
</g:if>
這樣代碼結(jié)構(gòu)個人覺得更加清晰簡單,類似freemarker的if elseif。
實現(xiàn):
要實現(xiàn)上面說的if elseif,需要繼承BodyTagSupport,利用BodyTagSupport的bodyContent的來實現(xiàn)該功能,這里不具體介紹如何實現(xiàn)jsp tag。直接貼出所有代碼,有興趣的自己看看。
public class IfTag extends BodyTagSupport{
public IfTag() {
super();
init();
}
@Override
public void release() {
super.release();
init();
}
@Override
public int doStartTag() throws JspException {
if(test){
this.succeeded();
}
return EVAL_BODY_BUFFERED;
}
@Override
public int doEndTag() throws JspException {
try {
if(subtagSucceeded)
pageContext.getOut().write(getBody());
} catch (IOException e) {
throw new JspException("IOError while writing the body: " + e.getMessage(), e);
}
init();
return super.doEndTag();
}
private String body = null; // 用于存放成功條件后的內(nèi)容
public void setBody(){
if(body == null){
body = bodyContent.getString().trim();
}
}
private String getBody(){
if(body == null)
return bodyContent.getString().trim();
else
return body;
}
/**
* 判斷if 或者 子 else if是否提交成功
*/
private boolean subtagSucceeded;
/**
* 子條件判斷成功
*/
public void succeeded(){
subtagSucceeded = true;
}
/**
* 是否已經(jīng)執(zhí)行完畢
* @return
*/
public boolean isSucceeded(){
return subtagSucceeded;
}
private void init() {
test = false;
subtagSucceeded = false;
body = null;
}
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
}
public class ElseIfTag extends BodyTagSupport{
public ElseIfTag() {
super();
init();
}
@Override
public int doStartTag() throws JspException {
Tag parent = getParent();
if(parent==null || !(parent instanceof IfTag)){
throw new JspTagException("else tag must inside if tag");
}
IfTag ifTag = (IfTag)parent;
if(ifTag.isSucceeded()){
// 已經(jīng)有執(zhí)行成功的條件,保存之前的html
ifTag.setBody();
}else if(test){ // 當前條件為true,之前無條件為true
ifTag.succeeded();
// 則清除之前的輸出
ifTag.getBodyContent().clearBody();
}
return EVAL_BODY_BUFFERED;
}
@Override
public void release() {
super.release();
init();
}
private void init() {
test = false;
}
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
}
public class ElseTag extends BodyTagSupport{
public void release() {
super.release();
}
public int doStartTag() throws JspException {
Tag parent = getParent();
if(parent==null || !(parent instanceof IfTag)){
throw new JspTagException("else tag must inside if tag");
}
IfTag ifTag = (IfTag)parent;
if(ifTag.isSucceeded()){
// 已經(jīng)有執(zhí)行成功的條件,保存之前的html
ifTag.setBody();
}else{
// 之前沒有的判斷沒有成功條件,則清除之前的輸出
ifTag.getBodyContent().clearBody();
ifTag.succeeded();
}
return EVAL_BODY_BUFFERED;
}
}
tld配置就不貼出來了,因為這個太簡單了,大家都知道的。