MVC_Spring - 폼 데이터 값 검증
프로그래밍 정리/Spring
2020. 1. 2. 15:00
반응형
MVC_Spring - 폼 데이터 값 검증
-폼 데이터 값 검증
- 만약 보내온 데이터 값이 없거나 공백이 있을 경우
- 입력페이지로 돌아가게 하는 방법이다.
-사용되는 인터페이스
- Validator
-구조
-실습 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @Controller public class StudentController { @RequestMapping("/studentForm") //로그인화면 public String studentForm() { return "createPage"; } @RequestMapping("/student/create") //로그인 검증 public String studentCreate(@ModelAttribute("student") Student student, BindingResult result) { //@ModelAttribute를 이용하여 Student 객체에 값 넣음 String page = "createDonePage"; StudentValidator validator = new StudentValidator(); //student검증 객체 만듬(따로 java파일 만들어놓은것) ┐ 대신 사용 가능 validator.validate(student, result); //student 객체를 검증하기위해 넣음, ┘─────────────┐ │ if(result.hasErrors()) { //ㄴ검증결과를 BindingResult에 넣기 위해 validate에 집어넣음 │ page = "createPage"; //검증이 잘못 됬을경우 로그인화면으로 감 │ } │ │ return page; │ } │ //--------------------------------------------------------------------------------------------------------------- │ @InitBinder │ protected void initBinder(WebDataBinder binder){ <───────────────────────────────────────────────────────────────────────┘ binder.setValidator(new StudentValidator()); } //--------------------------------------------------------------------------------------------------------------- } | cs |
-StudentValidator.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class StudentValidator implements Validator { //검증하기 위해 인터페이스 Validator를 사용 @Override public boolean supports(Class<?> arg0) { return Student.class.isAssignableFrom(arg0); // 검증할 객체의 클래스 타입 정보 } // 여기선 Student 객체 타입 검증 @Override public void validate(Object obj, Errors errors) { System.out.println("validate()"); Student student = (Student)obj; //--------------------------------------------------------------------------------------------------------------------- String studentName = student.getName(); if(studentName == null || studentName.trim().isEmpty()) { //Name값이 null or 공란존재 하면, errors에 에러 넣음 System.out.println("studentName is null or empty"); errors.rejectValue("name", "trouble"); } 또는 ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "trouble"); // (Validation유틸) null값 또는 공백 검사 //----------------------------------------------------------------------------------------------------------------------- int studentId = student.getId(); //ID값이 0이라면, errors에 에러 넣음 if(studentId == 0) { System.out.println("studentId is 0"); errors.rejectValue("id", "trouble"); } } } | cs |
-createPage.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>Insert title here</title> </head> <body> createPage.jsp <br /> <% String conPath = request.getContextPath(); %> <form action="student/create"> 이름 : <input type="text" name="name" value="${student.name}"> <br /> 아이디 : <input type="text" name="id" value="${student.id}"> <br /> <input type="submit" value="전송"> <br /> </form> </body> </html> | cs |
-createDonePage.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>Insert title here</title> </head> <body> createDonePage.jsp <br /> 이름 : ${student.name } <br /> 아이디 : ${student.id } </body> </html> | cs |
-Studen.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.javalec.spring_15_1_ex1_srpingex; public class Student { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } | cs |
-출력 결과
createPage.jsp 출력결과
createDonePage.jsp
반응형
'프로그래밍 정리 > Spring' 카테고리의 다른 글
MVC_Spring - @Autowired 사용하기 (0) | 2020.01.03 |
---|---|
MVC_Spring - JDBC 템플릿 사용하기 (0) | 2020.01.02 |
MVC_Spring - ID 또는 Password 체크 하기 (0) | 2020.01.02 |
MVC_Spring - Redirect 사용하기 (0) | 2019.12.31 |
MVC_Spring - @ModelAttribute 사용하기 (0) | 2019.12.31 |