- 依赖
- hibernate-validator
- 有spring-boot-starter-web就会有上边这个
- 常用注解
- @NotBlank(message = “用户昵称不能为空”)
- @Length(max = 12, message = “用户昵称不能超过12位”)
- @Pattern(regexp = “^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+d{8})$”, message = “手机号格式不正确”)
- @Min(value = 0, message = “性别选择不正确”)
- @Max(value = 2, message = “性别选择不正确”)
- 使用
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);
}
}
- 参考资料(来自慕课网)
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;
}
}
如何做文件上传
- 使用MultipartFile file接收
- 根据文件路径创建输出流,从MultipartFile获得输入流,输出到输出流
outputStream = new FileOutputStream(outFile); inputStream = file.getInputStream(); IOUtils.copy(inputStream, outputStream);
- 注意文件格式的限制
- 图片大小限制
spring
servlet:
multipart:
max-file-size: 512000 # 上传文件大小限制
max-request-size: 512000 # 请求大小限制
- 自定义捕获超出大小
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("文件大小超出限制");
}
}
如何使用属性资源文件
- 在resources创建资源文件
// file-upload-dev.properties
# 用户头像存放位置 file.userFaceLocation=/work/food/upload/userface
- 创建映射类
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;
}
}
- 使用映射类
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/");
}
}
- 解决swagger2文档看不了问题
1.方案: 使用多条sql解决
2. 示例



