发表于: 2019-12-22 23:00:34
1 1298
今天完成的事情:
尝试搭建一个message source 和 validator一起使用的校验方法
引入校验错误的依赖包
<!-- Hibernate Validator 校验错误需要的依赖包 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.4.GA</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.4</version>
</dependency>
student实体加两个验证约束注解 测试
// 验证字符串非空,且长度必须大于0
@NotBlank(message = "student.name.null")
private String name;
@NotNull(message = "student.qq.null")
private int qq;
@Max(value=30)
private int stunum;
配置一个spring bean
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
<property name="cacheSeconds" value="60"/>
</bean>
controller 用增加方法测试
@Validated就是对传入参数student进行校验 并将校验结果传入bindingresult
@RequestMapping(value = "/addstudent",method = RequestMethod.POST)
public ModelAndView addStudent(@Validated Student student,
BindingResult error) throws Exception {
ModelAndView mav = new ModelAndView();
if (error.hasErrors()) {
String message = error.getFieldError().getDefaultMessage();
throw new Exception(message);
}
ss.insertStudent(student);
mav.setViewName("redirect:/student/AllPage");
return mav;
}
新建一个类,把抛出的自定义异常交给ControllerAdvice处理
@ControllerAdvice是在类上声明的注解
其是用于封装一个切面所有属性的,包括切入点和需要织入的切面逻辑。
在这个代码里也可以这么理解
@ExceptionHandler
用于捕获Controller中抛出的指定类型的异常,从而达到不同类型的异常区别处理的目的
启动tomcat 容器进行测试
如果成功 跳转总页面
如果失败 跳转 fail.jsp
fail.jsp
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8" isErrorPage="true" %>
<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>失败啦失败啦失败啦</title>
</head>
<body>
<h1>添加失败<h1>
<tr>
<json:object>
<json:property name="message" value="${message}"/>
</json:object>
</tr>
</body>
</html>
输入数据 学号限制30 我这边填写33
跳转到fail
但也是没显示出来 message的自定义消息
fail 整体配置还有问题
明天计划的事情:
解决message source问题
服务器resin不知道为啥崩了
端口也没被占用
主页就是打不开...
评论