第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

springboot進(jìn)階

標(biāo)簽:
Java 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));
}
點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消