一、表单验证
1、创建Entity类:这里创建class Girl,在class声明的上一行加上@Entity注解
2、class Girl有成员变量age,在声明变量的上一行加上@Min(value=18, message = "未成年少女")
3、在Controller方法的参数列表对象Girl girl前面加上@Valid,然后加多一个参数:BindingResult bindingResult
4、在Controller方法体最前面加上:
if(bindingResult.hasErrors()) {//如果接收对象girl的age小于18
return bindingResult.getFieldError().getDefaultMessage();//返回"未成年少女"字符串
}
完整代码
/* 实体类 */
@Entity
class Gril {
@Min(value=18, message = "未成年少女")
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
/* controller下某个方法 */
public String getGrilString(@Valid Gril gril, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {//如果接收对象girl的age小于18
return bindingResult.getFieldError().getDefaultMessage();//返回"未成年少女"字符串
}
return "已成年少女";
}
二、AOP
1、添加maven依赖:spring-boot-starter-aop
2、创建类:HttpAspect
@Aspect
@Component
public class HttpAspect {
@Before("execution(publilc * com.test.controller.GirlController.getGirl(..))")
public void doBefore() {
System.out.println("在调用GirlController.getGirl方法前要做什么事");
//doService
}
@After("execution(publilc * com.test.controller.GirlController.getGirl(..))")
public void doAfter() {
System.out.println("在调用GirlController.getGirl方法后要做什么事");
//doService
}
}
第二种方式:定义公用切入点
@Aspect
@Component
public class HttpAspect {
@Pointcut("execution(publilc * com.test.controller.GirlController.getGirl(..))")
public void log() {//定义了公用的切入点
}
@Before("log()")
public void doBefore() {
System.out.println("在调用GirlController.getGirl方法前要做什么事");
//doService
}
@After("log()")
public void doAfter() {
System.out.println("在调用GirlController.getGirl方法后要做什么事");
//doService
}
}
3、在@Before、@After方法里面可以获取url、method、ip、类方法、参数等信息:
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
request.getRequestUrl();
//method
request.getMethod();
//ip
request.getRemoteAddr();
//类方法
joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//参数
joinPoint.getArgs();
}
4、获取Controller方法返回的结果
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {//这里的object就是Controller方法返回的实体对象
}
三、统一异常处理
1、创建Result类:
public class Result<T> {
private Integer code;//错误码
private String msg;//提示信息
private T data;//内容
//各个成员的get和set方法(此处省略)
}
2、创建ResultUtil工具类方便使用:
public class ResultUtil {
public static Result success(Object object) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
resutl.setData(Object);
return result;
}
public static Result success() {
return success(null);
}
public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
return result;
}
}
3、创建捕获Controller抛出去的异常的类:
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value="Exception.class")
@ResponseBody
public Result handle(Exception e) {
if( e instanceof CustomException) {//自定义异常类处理
CustomException customException = (CustomException) e;
return ResultUtil.error(customException.getCode(), customException.getMessage)
}
return ResultUtil.error(100, e.getMessage());
}
}
四、测试类
1、对Service
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void findOneTest() {
MyObj myObj = myService.findOne(23);
Assert.assertEquals(new Integer(23), myObj.getAge);
}
}
2、对Controller进行测试
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyServiceTest {
@Autowired
private MockMvc mvc;
@Test
public void findListTest() throws Exception {
//对Controller的RequestMapping为/findList的方法返回状态为200进行断言
mvc.perform(MockMvcRequestBuilders.get("/findList")).andExpect(MockMvcResultMatchers.status().isOk());
//对Controller的RequestMapping为/findList的方法返回内容为abc进行断言
mvc.perform(MockMvcRequestBuilders.get("/findList")).andExpect(MockMvcResultMatchers.content().string("abc"));
}
}