[Spring Boot]バリデーションチェックを実装するサンプル
1.pom.xmlに依頼関係を追加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2.バリテーションを追加
@Data
public class User {
@NotNull(message = "ユーザ名は必須")
private String name;
@NotNull(message = "パスワードは必須")
private String password;
}
@Data
public class User {
@NotNull(message = "ユーザ名は必須")
private String name;
@NotNull(message = "パスワードは必須")
private String password;
}
@Data public class User { @NotNull(message = "ユーザ名は必須") private String name; @NotNull(message = "パスワードは必須") private String password; }
3.BindingResultを使用してバリテーション結果を取得
@RestController
public class UserController {
@GetMapping("valid")
public String checkMsg(@Validated User user, BindingResult result) {/
System.out.println(user);
System.out.println("result=" + result);
if (result.hasErrors()) {
StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
sb.append(error.getDefaultMessage() + ";");
}
System.out.println(sb.toString());
return sb.toString();
}
return "success";
}
}
@RestController
public class UserController {
@GetMapping("valid")
public String checkMsg(@Validated User user, BindingResult result) {/
System.out.println(user);
System.out.println("result=" + result);
if (result.hasErrors()) {
StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
sb.append(error.getDefaultMessage() + ";");
}
System.out.println(sb.toString());
return sb.toString();
}
return "success";
}
}
@RestController public class UserController { @GetMapping("valid") public String checkMsg(@Validated User user, BindingResult result) {/ System.out.println(user); System.out.println("result=" + result); if (result.hasErrors()) { StringBuilder sb = new StringBuilder(); for (ObjectError error : result.getAllErrors()) { sb.append(error.getDefaultMessage() + ";"); } System.out.println(sb.toString()); return sb.toString(); } return "success"; } }
4.SpringBootクラス起動
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
@org.springframework.boot.autoconfigure.SpringBootApplication public class SpringBootApplication { public static void main(String[] args) { SpringApplication.run(SpringBootApplication.class, args); } }