xml 配置:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource"/>
</bean>
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven validator="validator"/>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:messages</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="60" />
</bean>
javaBean:
@Entity
@Table(name = "TEST")
public class Test implements Serializable{
private int id;
@NotBlank(message="{validate.notBlank.name}")
@Size(max=1,message="{validate.size.1.name}")
private String name;
controller:
@Controller
@RequestMapping(value = "/test")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/toAdd")
public ModelAndView toAdd() {
ModelAndView mv = new ModelAndView();
mv.addObject("test", new Test());
mv.setViewName("test/edit");
return mv;
}
@RequestMapping(value = "/edit")
public String edit(@ModelAttribute("test") @Valid Test test,BindingResult result) {
if(result.hasErrors()){
return "test/edit";
}else{
testService.persist(test);
}
return "forward:/test/list";
}
@RequestMapping(value="/json")
@ResponseBody
public String json(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("type", "json");
return JSON.toJSONString(map);
}
}