栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

架构师课学习笔记-第四周知识点

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

架构师课学习笔记-第四周知识点

如何使用Hibernate做数据校验
  1. 依赖
  • hibernate-validator
  • 有spring-boot-starter-web就会有上边这个
  1. 常用注解
  • @NotBlank(message = “用户昵称不能为空”)
  • @Length(max = 12, message = “用户昵称不能超过12位”)
  • @Pattern(regexp = “^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+d{8})$”, message = “手机号格式不正确”)
  • @Email
  • @Min(value = 0, message = “性别选择不正确”)
  • @Max(value = 2, message = “性别选择不正确”)
  1. 使用
public JSonResult update(
 @ApiParam(name = "userId", value = "用户id", required = true)
 @RequestParam String userId,
 // 关键
 @Valid
 @RequestBody CenterUserBO centerUserBO,
 HttpServletRequest request,
 HttpServletResponse response,
 // 关键
 BindingResult result
) {

    if (result.hasErrors()) {   // 关键
 List listError = result.getFieldErrors();
 Map map = new HashMap<>();
 for (FieldError error : listError) {
     map.put(error.getField(), error.getDefaultMessage());
 }
 return JSONResult.errorMap(map);
    }
}
  1. 参考资料(来自慕课网)

BO数据验证

  • 验证Bean:
public class ValBean {
    
    
    
    private Long id;

    @Max(value=20, message="{val.age.message}")   
    private Integer age;
    
    @NotBlank(message="{username.not.null}")
    @Length(max=6, min=3, message="{username.length}")
    private String username;

    @NotBlank(message="{pwd.not.null}")
    @Pattern(regexp="/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/", message="密码必须是6~10位数字和字母的组合")
    private String password;
    
    
    @Pattern(regexp="^((13[0-9])|(15[^4,D])|(18[0,5-9]))d{8}$", message="手机号格式不正确")
    private String phone;

    @Email(message="{email.format.error}")
    private String email;
}
  • 验证Controller:
@Controller
@RequestMapping(value = "/val")
public class ValidateController {

    @RequestMapping(value = "/val", method=RequestMethod.POST)
    @ResponseBody
    public LeeJSonResult val(@Valid @RequestBody ValBean bean, BindingResult result) throws Exception {
 
 if(result.hasErrors()){    
     //如果没有通过,跳转提示    
     Map map = getErrors(result);
     return LeeJSONResult.error(map);
 }else{    
     //继续业务逻辑    
 } 
 
 return LeeJSONResult.ok();
    }
    
    private Map getErrors(BindingResult result) {
 Map map = new HashMap();
 List list = result.getFieldErrors();
 for (FieldError error : list) {
     System.out.println("error.getField():" + error.getField());
     System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());
     
     map.put(error.getField(), error.getDefaultMessage());
 }
 return map;
    }
}
如何做文件上传
  1. 使用MultipartFile file接收
  2. 根据文件路径创建输出流,从MultipartFile获得输入流,输出到输出流
outputStream = new FileOutputStream(outFile);
inputStream = file.getInputStream();
IOUtils.copy(inputStream, outputStream);
  1. 注意文件格式的限制
  2. 图片大小限制
spring
  servlet:
    multipart:
      max-file-size: 512000     # 上传文件大小限制
      max-request-size: 512000  # 请求大小限制
  1. 自定义捕获超出大小
package com.xiong.exception;

import com.xiong.common.utils.JSONResult;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
public class CustomExceptionHandler {
    public JSonResult handlerMaxUploadFile(MaxUploadSizeExceededException e) {
 return JSONResult.errorMsg("文件大小超出限制");
    }
}

如何使用属性资源文件
  1. 在resources创建资源文件

// file-upload-dev.properties

# 用户头像存放位置
file.userFaceLocation=/work/food/upload/userface
  1. 创建映射类
package com.xiong.resources;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:file-upload-dev.properties")
@ConfigurationProperties(prefix = "file")
public class FileUpload {
    private String userFaceLocation;

    public String getUserFaceLocation() {
 return userFaceLocation;
    }

    public void setUserFaceLocation(String userFaceLocation) {
 this.userFaceLocation = userFaceLocation;
    }
}

  1. 使用映射类
springboot如何做静态资源服务
package com.xiong.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    // 实现静态资源的映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
 registry.addResourceHandler("/**")
  .addResourceLocations("file:/work/food/upload/");
    }
}
  1. 解决swagger2文档看不了问题
pagehelper嵌套分页bug解决

1.方案: 使用多条sql解决
2. 示例




    
 
 
 
 
 
 
 
 
     
   
 
    

    

    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/239292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号