1. 라이브러리
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.5.2</version> </dependency>
2. CMRespDto
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Data public class CMRespDto<T> { private int code; //1(성공), -1(실패) private String message; private T data; }
3. CustomValidationException
import java.util.Map; public class CustomValidationException extends RuntimeException { private static final long serialVersionUID = -807520916259076805L; private String message; private Map<String,String> errorMap; public CustomValidationException(String message, Map<String,String> errorMap) { super(message); this.message=message; this.errorMap=errorMap; } public Map<String,String> getErrorMap(){ return errorMap; } }
CustomValidationApiException
import java.util.Map; public class CustomValidationApiException extends RuntimeException { private static final long serialVersionUID = -807520916259076805L; private Map<String,String> errorMap; public CustomValidationApiException(String message) { super(message); } public CustomValidationApiException(String message, Map<String,String> errorMap) { super(message); this.errorMap=errorMap; } public Map<String,String> getErrorMap(){ return errorMap; } }
4.ControllerExceptionHandler
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import com.cos.photogramstart.handler.ex.CustomApiException; import com.cos.photogramstart.handler.ex.CustomValidationApiException; import com.cos.photogramstart.handler.ex.CustomValidationException; import com.cos.photogramstart.utils.Script; import com.cos.photogramstart.web.dto.CMRespDto; @RestController @ControllerAdvice public class ControllerExceptionHandler { @ExceptionHandler(CustomValidationException.class) public String validationException(CustomValidationException e) { //CMRespDto,Script 비교 //1.클라이언트에게 응답할 때는 Script 좋음. //2.Ajax통신 - CMRespDto //3.Android 통신 - CMRespDto if(e.getErrorMap()!=null) { return Script.back(e.getErrorMap().toString()); }else { return Script.back(e.getMessage()); } } @ExceptionHandler(CustomValidationApiException.class) public ResponseEntity<?> validationApiException(CustomValidationApiException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new CMRespDto<Object>(-1, e.getMessage(), e.getErrorMap())) ; } @ExceptionHandler(CustomApiException.class) public ResponseEntity<?> apiException(CustomApiException e){ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new CMRespDto(-1, e.getMessage(), null)) ; } }
===================================================================================================================
추가 참조
SignupDto
import javax.validation.constraints.Email; import javax.validation.constraints.Max; import javax.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Length; import com.cos.photogramstart.domain.user.User; import lombok.Data; @Data //Getter, Setter public class SignupDto { @NotBlank(message="유저명을 입력해주세요.") @Length(max = 20) private String username; @NotBlank private String password; @NotBlank(message="이메일을 입력해주세요.") @Email(message = "올바른 이메일 주소를 입력해 주세요.") private String email; @NotBlank private String name; public User toEntity() { return User.builder() .username(username) .password(password) .email(email) .name(name) .build(); } }
AuthController
/** * 회원가입버튼-> /auth/signup -> /auth/signin * 회원가입버튼 x * @return */ @PostMapping("/auth/signup") public String signup(@Valid SignupDto signupDto, Errors errors, Model model) { // key=value(x-www-form-unlencoded) log.info("** 회원가입 처리 {}", signupDto.toString()); if(errors.hasErrors()) { Map<String,String> erroMap=new HashMap<>(); for(FieldError error : errors.getFieldErrors() ) { System.out.println("======================================"); erroMap.put(error.getField(), error.getDefaultMessage()); System.out.println("======================================"); } throw new CustomValidationException("유효성검사 실패함 " , erroMap); } if(errors.hasErrors()) { log.info("*************** errors : {}", errors.toString()); return "auth/signup"; } //이메일 중복 체크 if(authService.existsByEmail(signupDto.getEmail())){ log.info("***** 이메일 중복 : {}", signupDto); errors.rejectValue("email", "email" , "이메일 중복"); return "auth/signup"; } User user=signupDto.toEntity(); log.info(user.toString()); authService.insertUser(user); return "redirect:/auth/signin"; }
signup.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!--회원가입 인풋--> <form:form class="login__input" action="/auth/signup" method="post" modelAttribute="signupDto"> <!-- required="required" --> <input type="text" name="username" placeholder="유저네임" value="${signupDto.username}" /> <div class="error"><form:errors path="username"/></div> <input type="password" name="password" placeholder="패스워드" required="required" /> <div class="error"><form:errors path="password"/></div> <input type="email" name="email" placeholder="이메일" required="required" value="${signupDto.email}" /> <div class="error"><form:errors path="email"/></div> <input type="text" name="name" placeholder="이름" value="${signupDto.name}" /> <div class="error"><form:errors path="name"/></div> <button>가입</button> </form:form>
UserApiController
import java.util.HashMap; import java.util.Map; import javax.validation.Valid; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RestController; import com.cos.photogramstart.config.auth.PrincipalDetails; import com.cos.photogramstart.domain.user.User; import com.cos.photogramstart.handler.ex.CustomValidationApiException; import com.cos.photogramstart.service.UserService; import com.cos.photogramstart.web.dto.CMRespDto; import com.cos.photogramstart.web.dto.user.UserUpdateDto; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; @RestController @RequiredArgsConstructor @Log4j2 public class UserApiController { private final UserService userService; @PutMapping("/api/user/{id}") public CMRespDto<?> udpate(@PathVariable int id, @Valid UserUpdateDto userUpdateDto , Errors errors, //꼭 @Valid 가 적혀있는 다름 파라미터에 적어야 됨 @AuthenticationPrincipal PrincipalDetails principalDetails) { if(errors.hasErrors()) { Map<String,String> erroMap=new HashMap<>(); for(FieldError error : errors.getFieldErrors()) { erroMap.put(error.getField(), error.getDefaultMessage()); } throw new CustomValidationApiException("유효성검사 실패함 " , erroMap); }else { User userEntity=userService.회원수정(id, userUpdateDto.toEntity()); principalDetails.setUser(userEntity); log.info("****업데이트 유저 정보 데이터 : {}", userEntity.toString()); return new CMRespDto<>(1, "회원수정완료", userEntity); } } }
CustomApiException
public class CustomApiException extends RuntimeException { private static final long serialVersionUID = -807520916259076805L; public CustomApiException(String message) { super(message); } }
CustomValidationException
import java.util.Map; public class CustomValidationException extends RuntimeException { private static final long serialVersionUID = -807520916259076805L; private Map<String, String> errorMap; public CustomValidationException(String message, Map<String, String> errorMap) { super(message); this.errorMap = errorMap; } public Map<String, String> getErrorMap(){ return errorMap; }
소스 :
https://github.com/braverokmc79/EaszUp-Springboot-Photogram-Start
댓글 ( 4)
댓글 남기기