1 16 17 package org.springframework.web.servlet.tags.form; 18 19 import java.util.ArrayList ; 20 import java.util.Arrays ; 21 import java.util.List ; 22 23 import javax.servlet.jsp.JspException ; 24 import javax.servlet.jsp.PageContext ; 25 import javax.servlet.jsp.tagext.BodyTag ; 26 27 import org.springframework.util.Assert; 28 import org.springframework.util.ObjectUtils; 29 30 46 public class ErrorsTag extends AbstractHtmlElementBodyTag implements BodyTag { 47 48 52 public static final String MESSAGES_ATTRIBUTE = "messages"; 53 54 57 public static final String SPAN_TAG = "span"; 58 59 60 private String element = SPAN_TAG; 61 62 private String delimiter = "<br/>"; 63 64 67 private Object oldMessages; 68 69 private boolean errorMessagesWereExposed; 70 71 72 76 public void setElement(String element) { 77 Assert.hasText(element, "'element' cannot be null or blank"); 78 this.element = element; 79 } 80 81 84 public String getElement() { 85 return this.element; 86 } 87 88 92 public void setDelimiter(String delimiter) { 93 this.delimiter = delimiter; 94 } 95 96 99 public String getDelimiter() { 100 return this.delimiter; 101 } 102 103 104 110 protected String getName() throws JspException { 111 return ""; 112 } 113 114 120 protected String autogenerateId() throws JspException { 121 return getCompletePath() + ".errors"; 122 } 123 124 129 protected boolean shouldRender() throws JspException { 130 try { 131 return getBindStatus().isError(); 132 } 133 catch (IllegalStateException ex) { 134 return false; 136 } 137 } 138 139 protected void renderDefaultContent(TagWriter tagWriter) throws JspException { 140 tagWriter.startTag(getElement()); 141 writeDefaultAttributes(tagWriter); 142 String delimiter = ObjectUtils.getDisplayString(evaluate("delimiter", getDelimiter())); 143 String [] errorMessages = getBindStatus().getErrorMessages(); 144 for (int i = 0; i < errorMessages.length; i++) { 145 String errorMessage = errorMessages[i]; 146 if (i > 0) { 147 tagWriter.appendValue(delimiter); 148 } 149 tagWriter.appendValue(getDisplayString(errorMessage)); 150 } 151 tagWriter.endTag(); 152 } 153 154 160 protected void exposeAttributes() throws JspException { 161 List errorMessages = new ArrayList (); 162 errorMessages.addAll(Arrays.asList(getBindStatus().getErrorMessages())); 163 this.oldMessages = this.pageContext.getAttribute(MESSAGES_ATTRIBUTE, PageContext.PAGE_SCOPE); 164 this.pageContext.setAttribute(MESSAGES_ATTRIBUTE, errorMessages, PageContext.PAGE_SCOPE); 165 this.errorMessagesWereExposed = true; 166 } 167 168 173 protected void removeAttributes() { 174 if (this.errorMessagesWereExposed) { 175 if (this.oldMessages != null) { 176 this.pageContext.setAttribute(MESSAGES_ATTRIBUTE, this.oldMessages, PageContext.PAGE_SCOPE); 177 this.oldMessages = null; 178 } 179 else { 180 this.pageContext.removeAttribute(MESSAGES_ATTRIBUTE, PageContext.PAGE_SCOPE); 181 } 182 } 183 } 184 185 } 186 | Popular Tags |