<!-- 引入属性文件 -->
<!--加载config.properties文件-->
<context:property-placeholder location="classpath:config.properties" />
<!-- 国际化的消息资源文件 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:包名/包名/包名/包名/文件名(不要后缀)</value>
</list>
</property>
<!--defaultEncoding 默认编码是ISO-8859-1 这里设置为UTF-8-->
<property name="defaultEncoding" value="UTF-8"/>
<!--cacheSeconds 设置缓存文件加载性能的秒数 默认为-1-->
<property name="cacheSeconds" value="60"/>
</bean>
<!-- 会自动注册了validator ConversionService -->
<mvc:annotation-driven validator="validator" conversion-service="conversion-service"/>
<!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource"/>
</bean>
@RequestMapping(value="/save",method=RequestMethod.POST)
public String add(@Valid @ModelAttribute("cmsDifficultyLevel")CmsDifficultyLevel cmsDifficultyLevel,Errors errors,Model model){
//**参数@Valid 不能丢 Errors errors必须放在实体对象后不然报 org.springframework.validation.BeanPropertyBindingResult: 1 errors
if (errors.hasErrors()) {//判断是否出错
model.addAttribute("cmsDifficultyLevel", cmsDifficultyLevel);
return "cms/difficulty/difficulty_add";//这里的路径就是你进入当前页面的路径
}
if (cmsDifficultyLevel.getLevelId() != null) {
CmsDifficultyLevel difficultLevel = difficutlyLevelService.getById(cmsDifficultyLevel.getLevelId());
difficultLevel.setLevelName(cmsDifficultyLevel.getLevelName());
difficutlyLevelService.update(difficultLevel);
} else {
difficutlyLevelService.save(cmsDifficultyLevel);
}
return "redirect:/cms/difficulty";
}
jsp页面错误打印信息
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<span>${errorMsg}</span>
<form:form commandName="cmsDifficultyLevel" class="form-horizontal" method="post" action="${path}/cms/difficulty/save">
<form:errors path="*" cssStyle="color:red"></form:errors>
</form:form>
实体 是用@NotBlank(message = "难易程度名不能为空")
本文出自 “一直在爬坑” 博客,谢绝转载!