慕课网链接
表单数据的验证
在pojo类属性的上面添加注解
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
@NotBlank(message = "这个字段必传")
private String cupSize;
@Min(value = 18, message = "未成年少女禁止入门")
// @NotNull
// @Max()
// @Length()
private Integer age;
}
校验使用(使用@valid来验证)
@PostMapping(value = "/girls")
public Result girlAdd(@Valid Girl girl, BindingResult bindingResult) {
//使用BindingResult对象输出校验对象的出错信息
if (bindingResult.hasErrors()) {
return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
}
girl.setCupSize(girl.getCupSize());
girl.setAge(girl.getAge());
return ResultUtil.success(girlRepository.save(girl));
}
AOP统一处理
在pom中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
并添加AOP操作类
@Aspect
@Component
public class HttpAspect {
}
添加方法
@Before("execution(public * com.controller.GirlController.*(..))")
public void before() {
System.out.println("指定方法之前执行")
}
@After("execution(public * com.controller.GirlController.*(..))")
public void after() {
System.out.println("指定方法之后执行")
}
/**
* @Before: 方法执行之前
* @After: 方法执行之后
* @AfterReturning: 方法返回之后
* (..)表示任何参数都会被拦截
* *代表所有
*/
如果多次为这些方法进行切面编程可使用@Pointcut注解
@Ponitcut("execution(public * com.controller.GirlController.*(..))")
public void log(){}
@Before("log()")
public void before() {
System.out.println("指定方法之前执行")
}
@After("log()")
public void after() {
System.out.println("指定方法之后执行")
}
实际项目开发中也不推荐使用控制台输出(使用日志输出)
@Aspect
@Component
public class HttpAspect {
private final static Looger logger=LoggerFactory.getLogger;
@After("log()")
public void doAfter() {
logger.info("指定方法之后执行")
}
//输出方法的放回结果
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
logger.info("response={}", object.toString());
}
}
日志添加有用信息(请求有关的数据)
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}", request.getRequestURL());
//method
logger.info("method={}", request.getMethod());
//ip
logger.info("ip={}", request.getRemoteAddr());
//类方法
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//参数
logger.info("args={}", joinPoint.getArgs());
}
异常的捕获和处理
统一异常处理的步骤
-
建立一个Result类 :http请求返回的最外层对象,包括code msg data
-
写一个工具类:优化代码(减少重复代码)
//===========自定义异常类(spring只能捕获运行时异常,所以继承RuntimeException类)=============
public class GirlException extends RuntimeException{
private Integer code;
public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code=resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
//==========异常捕获===========
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger=LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value=Exception.class)
@ResponseBody
public Result handle(Exception e) {
if(e instanceof GirlException) {
GirlException girlException=(GirlException)e;
return ResultUitl.error(girlException.getCode(), girlException.getMessage());
}else {
logger.error("【系统异常】{}",e);
return ResultUitl.error(-1, e.getMessage());
}
}
}
异常出现的情况
//=========GirlController=======
@RequestMapping("/girlGetAge/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception {
girlService.getAge(id);
}
//==========GirlService==============
//异常抛给controller
public void getAge(Integer id) throws Exception{
Girl girl=girlRepository.findOne(id);
Integer age=girl.getAge();
if(age<10) {
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if(age>10 && age<16) {
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}
}
//=========ResultEnum==========
public enum ResultEnum {
UNKONW_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"你在上小学"),
MIDDLE_SCHOOL(101,"你在上初中"),
;
private Integer code;
private String msg;
get\set方法......
}
单元测试
测试controller
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GrilController {
@Autowired
private MockMvc mvc;
@Test
public void girlList() throws Exception {
mvc.perform(
MockMvcRequestBuilders.get("/girl/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
}
}
来源:oschina
链接:https://my.oschina.net/u/3908739/blog/2208831