代码之家  ›  专栏  ›  技术社区  ›  Arthur Ronald

如何设置Spring中每个错误字段中使用的全局前缀和后缀?

  •  0
  • Arthur Ronald  · 技术社区  · 16 年前

    errors.prefix=<div class="error">
    errors.suffix=</div>
    

    那么,我如何通过使用Spring表单标签来获得相同的效果<表单:错误?

    2 回复  |  直到 16 年前
        1
  •  2
  •   ChssPly76    16 年前

    你为什么要这么做?Spring在内部呈现错误 <span> cssClass 属性 <spring:errors> 。然后,您可以通过CSS按自己的方式设置样式。

    <跨度> customizable 同样,显然(我刚刚看了,从来没有需要自己改变它):

    <spring:errors element="div" cssClass="errorBox" path="..."/>
    

    将错误包装在 <div class="errorBox"></div>

        2
  •  0
  •   Arthur Ronald    16 年前

    有一个解决方法,但您必须实现自定义MessageSource

    public class CustomMessageSource extends ResourceBundleMessageSource {
    
        private String prefix;
        private String suffix;
    
        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    
        public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
            if(code.startsWith("typeMismatch"))
                return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
    
            if(code.startsWith("errors"))
                return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
    
            return super.getMessage(code, args, defaultMessage, locale);
        }
    
        public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
            if(code.startsWith("typeMismatch"))
                return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
    
            if(code.startsWith("errors"))
                return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
    
            return super.getMessage(code, args, locale);
        }
    
        public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
            String [] errors = resolvable.getCodes();
            for(String error: errors) {
                if(error.startsWith("typeMismatch"))
                    return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
    
                if(error.startsWith("errors"))
                    return this.prefix + super.getMessage(resolvable, locale) + this.suffix;
            }
    
            return super.getMessage(resolvable, locale);
        }
    
    }
    

    <bean id="messageSource" class="br.com.some.CustomMessageSource">
        <property name="prefix" value="<div class=\"error\">"/>
        <property name="suffix" value="</div>"/>
        <property name="basenames">
            <list>
                 <value>messages</value>
                 <value>errors</value>
            </list>
        </property name="basenames">
    </bean>