目录
1.新建品牌分类
2.导入前端代码
3.页面优化
4.阿里云开通oss
5.文件上传
6.表单后端校验 JSR303
在renren-fast客户端中,创建二级菜单,注意菜单的路由
使用spring cloud Alibaba-oss,并将其创建第三方模块
参考官方文档:spring cloudAlibaba-oss
spring boot和cloud的版本不要过高
com.alibaba.cloud
spring-cloud-starter-alicloud-oss
1.将其注册到服务中心
2.配置中心
3.微服务名称4.端口号
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.20.50:1111
config:
server-addr: 192.168.20.50:1111
namespace: 75307413-52f9-4045-8d34-abaceeced6de
alicloud:
access-key: =====8DK3oQbqru1Zsyjezy
secret-key: =====zNIZTc4QjUxEMY78ZyWCbkrIY
oss:
endpoint: =====beijing.aliyuncs.com
bucket: hqdmdxz-gulimall
application:
name: gulimall-third-party
server:
port: 30000
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@RequestMapping("/oss/policy")
public R policy() {
//https://hqdmdxz-gulimall.oss-cn-beijing.aliyuncs.com/hahaha.jpg
String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
// String callbackUrl = "http://88.88.88.88:8888";
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format + "/"; // 用户上传文件时指定的前缀。
Map respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap = new LinkedHashMap();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return R.ok().put("data",respMap);
}
}
在阿里云上设置跨域设置,允许所有post请求
@RequestMapping("/save")
//@RequiresPermissions("product:brand:save")
public R save(@Valid @RequestBody BrandEntity brand, BindingResult result) {
if (result.hasErrors()) {
Map map=new HashMap<>();
//1.获取校验的结果
result.getFieldErrors().forEach((item)->{
//2.获取的错误提示
String message = item.getDefaultMessage();
//3.获取错误的属性的名字
String field = item.getField();
map.put(field,message);
});
return R.error(400,"提交的数据不合法").put("data",map);
} else {
brandService.save(brand);
}
return R.ok();
}
上面的单个返回异常会反复操作,我们不使用BindingResult,而是使用一个类封装所有异常信息,当校验出现错误时,直接去异常嘞找即可。
- @ControllerAdvice注解是一个全局异常处理器,用于处理控制器层(Controller层)的异常。
@Slf4j
//RestControllerAdvice=@ControllerAdvice+@ResponseBody
@RestControllerAdvice(basePackages = "com.xz.gulimall.product.controller")
public class GuLiMallExceptionControllerAdvice {
//精确匹配
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildException(MethodArgumentNotValidException e) {
log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
BindingResult result = e.getBindingResult();
Map map = new HashMap<>();
result.getFieldErrors().forEach((fieldError) -> {
map.put(fieldError.getField(), fieldError.getDefaultMessage());
});
return R.error(BizCodeEnume.VALD_EXCEPTION.getCode(), BizCodeEnume.VALD_EXCEPTION.getMsg()).put("data", map);
}
//兜底异常处理
@ExceptionHandler(value = Throwable.class)
public R handleException(Throwable throwable) {
return R.error(BizCodeEnume.UNKONW_EXCEPTION.getCode(),BizCodeEnume.UNKONW_EXCEPTION.getMsg());
}
}
在之后,我们所有的异常直接抛出,全都用异常类处理,这也产生一个问题,就是状态码不统一,如何使用不同的状态码》》》》我们在公共模块封装一个状态码枚举
/**
* 定义系统状态码
*/
public enum BizCodeEnume {
UNKONW_EXCEPTION(10000, "系统未知异常"),
VALD_EXCEPTION(10001,"参数格式校验失败");
private Integer code;
private String msg;
BizCodeEnume(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
之后直接待用枚举中相对应的状态码和异常信息即可~
1.给校验注解标注什么时候开始校验
2.使用@ValidDated,标记校验分组
注:不添加分组校验,添加的校验功能注解是不生效的
@RequestMapping("/save")
//@RequiresPermissions("product:brand:save")
public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand /*,BindingResult result*/) {
brandService.save(brand);
return R.ok();
}
1.编写一个自定义的校验注解,并创建配置文件
@Documented
@Constraint(
validatedBy = {
ListValueConstrainValidator.class//自定义校验器,与注解产生关联
}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValue {
String message() default "{com.xz.common.vaild.ListValue.message}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
int[] vals() default {};
}
2.自定义校验器
public class ListValueConstrainValidator implements ConstraintValidator {
private Set set=new HashSet<>();
//初始化方法
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
for (int val: vals){
set.add(val);
}
}
//判断是否校验成功
/**
*
* @param value : 需要校验的值
* @param context
* @return
*/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
3.校验注解与校验器产生关系,在注解中添加校验器类