springboot进阶

表单验证

  • @Valid 验证注解
  • BindingResult 返回结果
  • bindingResult.getFieldError().getDefaultMessage() 获取错误信息
public void create(@Valid Luckymoney luckymoney, BindingResult bindingResult){
    if (bindingResult.hasErrors()) {
        // bindingResult.getFieldError().getDefaultMessage()
    }
}

AOP处理请求

  • 类注解: @Aspect @Component
  • 切点: @Pointcut
  • 调用之前:@Before
  • 调用之后:@After

输出日志
  • 所属包:org.slf4j.Logger
  • 在哪个类打印日志:HttpAspect.class
  • 打印日志方法
    • logger.info()
    • logger.error();
    • logger.debug();
    • logger.warn();
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
指定切点
  • 括号中填写路径
  • *代表所有方法,也可以指定某个方法
  • … 代表任何参数都会被拦截
 @Pointcut("execution(public * com.lxh.summer.controller.LuckymoneyController.*(..))")
 public void log(){

}
调用之前及调用之后
  • log()指定切点
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
    logger.info("before");
}    
@After("log()")
public void doAfter() {
    logger.info("after");
}
返回结果
  • returning返回结果,pointcut切点
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
    logger.info("response={}", object);
}
记录http请求
// 记录http请求
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("classMethod={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
// 参数
logger.info("args={}", joinPoint.getArgs());

统一异常处理

流程

  1. 定义返回数据格式
  2. 定义统一数据处理
  3. 捕获异常
  4. 自定义异常
  5. 异常枚举定义

具体操作

定义数据格式
public class Result<T> {
    /* 错误码*/
    private Integer code;
    /* 信息*/
    private String msg;
    /* 数据*/
    private T data;
    // getter setter 略
}
定义统一数据处理
public class ResultUtil {

    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg(ResultEnum.SUCCESS.getMessage());
        result.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(code);
        result.setMsg(msg);
        return result;
    }
}
捕获异常
  • 类注解:@ControllerAdvice
  • 方法注解:
    • @ExceptionHandler(value = Exception.class) 指定捕获哪个类的异常
    • @ResponseBody 返回json格式
  • 是否是自定义异常: e instanceof LuckymoneyException
@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 LuckymoneyException) {
            LuckymoneyException luckymoneyException = (LuckymoneyException) e;
            return ResultUtil.error(luckymoneyException.getCode(), luckymoneyException.getMessage());
        }
        logger.error("系统错误", e);
        return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMessage());
    }
}
自定义异常
  • RuntimeException:必须继承运行时异常,否则框架处理不了
public class LuckymoneyException extends RuntimeException {

    private Integer code;

    public LuckymoneyException(ResultEnum resultEnum) {
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}
异常枚举定义
public enum  ResultEnum {
    UNKNOWN_ERROR(-500, "未知错误"),
    SMALL_LUCKY(0, "红包太小了"),
    BIG_LUCKY(1, "红包太大了"),
    SUCCESS(200, "成功"),
    FAILURE(400, "失败")
    ;

    private Integer code;

    private String message;

    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}
示例

service层

public Luckymoney getMoney(Integer id) throws Exception{
    Luckymoney luckymoney = respository.findById(id).orElse(null);
    BigDecimal money = luckymoney.getMoney();
    if (money.compareTo(new BigDecimal(100)) < 0){
        // 抛出自定义异常
        throw new LuckymoneyException(ResultEnum.SMALL_LUCKY);
    } else if (money.compareTo(new BigDecimal(100)) > 0) {
        throw new LuckymoneyException(ResultEnum.BIG_LUCKY);
    } else {
        return luckymoney;
    }
}

controller层

@GetMapping("/luckymoney/{id}")
public Result getMoneyById(@PathVariable("id") Integer id) throws Exception{
    // 返回统一结果
    return ResultUtil.success(servive.getMoney(id));
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值