首页 > 其他分享 >SpringBoot IO

SpringBoot IO

时间:2022-11-07 23:14:25浏览次数:57  
标签:5.1 java SpringBoot mobile static IO import annotation

目录

1、Caching

1.1、Supported Cache Providers

2、Hazelcast

3、Quartz Scheduler

4、Sending Email

5、Validation

5.1、验证手机号是否有效示例

5.1.1、定义验证注解类

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { MobileValidator.class })
public @interface IsMobile {

    boolean required() default true;

    String message() default "手机号码格式错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

5.1.2、定义验证核心类

import static org.springframework.util.StringUtils.hasText;

import java.util.regex.Pattern;

public class MobileValidator implements javax.validation.ConstraintValidator<IsMobile, String> {

    private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");
    private boolean              required       = false;

    @Override
    public boolean isValid(String value, javax.validation.ConstraintValidatorContext context) {
        if (required) {
            return isMobile(value);
        } else {
            if (!hasText(value)) {
                return true;
            } else {
                return isMobile(value);
            }
        }
    }

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    private boolean isMobile(String mobile) {
        if (!hasText(mobile)) {
            return false;
        }

        return mobile_pattern.matcher(mobile).matches();
    }
}

5.1.3、验证异常统一处理

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return new HashMap<String, Object>(2) {

            private static final long serialVersionUID = 6073161079995491657L;

            {
                put("code", 500);
                put("msg", e.getBindingResult().getFieldError().getDefaultMessage());
            }

        };
    }

}

5.1.4、控制器引入验证

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.validation.constraints.NotBlank;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.cnblogs.javalouvre.controller.validator.IsMobile;

@RestController
public class IndexController {

    @PostMapping(path = "/")
    public Map<String, Object> execute(@Validated @RequestBody User user) {
        return new HashMap<String, Object>(3) {

            private static final long serialVersionUID = 6073161079995491657L;

            {
                put("code", 1);
                put("msg", "OK");
                put("data", Collections.singletonMap("num", UUID.randomUUID().toString().replace("-", "")));
            }

        };
    }
}

class User {

    @NotBlank(message = "手机号不可为空")
    @IsMobile
    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

}

5.1.5、启动服务验证

5.1.5.1、验证正确

$ curl -L -X POST 'http://127.0.0.1:8080' \
> -H 'Content-Type: application/json' \
> --data-raw '{
>     "mobile": "13800138000"
> }'
{"msg":"OK","data":{"num":"94694a9e567241999bd4259aca7b7e7a"},"code":1}

5.1.5.2、验证失败

$ curl -L -X POST 'http://127.0.0.1:8080' -H 'Content-Type: application/json' --data-raw '{
    "mobile": "03800138000"
}'
{"msg":"手机号码格式错误","code":500}

6、Calling REST Services

7、Web Services

8、Distributed Transactions With JTA

9、What to Read Next

标签:5.1,java,SpringBoot,mobile,static,IO,import,annotation
From: https://www.cnblogs.com/javalouvre/p/16867843.html

相关文章

  • Spring的IoC容器之BeanFactory
    SpringIoC容器之BeanFactory首先,Spring提供了两种容器类型:BeanFactory和ApplicationContext。BeanFactory:基础容器类型,提供了完整的IoC服务支持。默认采用延迟......
  • springboot多环境配置
    springboot整合多个环境配置springboot默认读取配置文件名称application,且多个环境配置文件必须按照如下命名Application-dev.yml开发环境application-test.yml......
  • springboot整合nacos config详解
    springboot整合nacos详解@value:读取application文件@ConfigurationProperties:读取指定文件@PropertySource:自定义文件引入@PropertySource+@Value:读取自定义文件@Pro......
  • 安卓12 查看gpio
    安卓12 查看gpiocat/sys/devices/platform/pinctrl@1000b000/mt_gpiochmod 777 mt_gpioecho "out 154 0" > mt_gpio cd/sys/class/leds/ 查看电池状况......
  • boostrap.yml 与 application.yml 详解
    boostrap.yml与application.yml详解​ 官方解释:SpringBoot中有两种上下文,bootstrap和applicationbootstrap:应用程序的父上下文,即bootstrap加载优先于applicato......
  • wdf框架之WdfVersionBind函数分析(2)
    接​​前篇​​,这篇一起来看下WdfVersionBind函数的第4个参数:WdfDriverGlobals。经过前面一番波折,WdfVersionBind总算找到了Wdf01000.sys!_WDF_LIBRARY_INFO结构。接下去,它......
  • 京东云开发者|深入JDK中的Optional
    概述:Optional最早是Google公司Guava中的概念,代表的是可选值。Optional类从Java8版本开始加入豪华套餐,主要为了解决程序中的NPE问题,从而使得更少的显式判空,防止代码污染,另一......
  • Minio分布式文件存储
    packagewangbiao.config.minio;importcom.fasterxml.jackson.core.JsonProcessingException;importio.minio.*;importio.minio.errors.*;importio.minio.messag......
  • 调试遗漏IoStartNextPacket引起的阻塞
       前面​​driververifier检测驱动死锁 ​​一文中本想检测一下驱动中潜在的死锁来解决驱动无响应的bug,然而并没有实质性的进展。后来通过一系列的调试终于找到了......
  • 【THM】Linux Privilege Escalation(Linux权限提升基础)-学习
    本文相关的TryHackMe实验房间链接:https://tryhackme.com/room/linprivesc通过学习相关知识点:了解Linux权限提升的基础知识,从枚举到利用,了解多种不同的权限提升技术。介......