엘라의 개발 스케치 Note
[TIL] 내일배움캠프 44일차(23.06.27.) - 과제 작성 중 오류 문제 해결 본문
To-do
- 스프링 숙련 복습 및 개인과제 lv.2 작성
TIL
- password Encoder no bean 문제 해결
* [ERROR] Could not autowire. No beans of 'PasswordEncoder' type found
-> 구글링을 통해 해결
-> PasswordEncoder 가 담긴 config에 @EnableWebSecurity를 빠뜨린 문제였음. 넣어주니 해결되었음!
- Response Body에 객체인 Reponse가 반환되지 않는 문제
* Controller에 반환 타입으로 객체를 넣어두었으나 Response Body에 아무것도 반환되지 않는 문제가 발생함
-> 코드를 다시 한번 살펴 보았음
-> 해당 메서드에 @ResponseBody를 달아두지도 않고, Controller도 @Controller로 되어 있는 것을 확인
-> @Controller를 @Rest Controller로 바꿔주어 해결
*** @RestController = @Controller + @ResponseBody -> Json 형태로 객체 데이터 반환하기
- Validation이 제대로 작동하지 않는 문제
* RequestDto 상의 Validation이 제대로 동작하지 않는 문제가 발생함
-> 구글링을 아무리 해도 적당한 해결이 보이지 않아 코드를 다시 한번 살펴보고 이것저것 시도해 봄
ⓐ @RequestBody @Valid ~Dto 의 순서가 문제인가싶어 @Valid @RequestBody ~Dto로 시도 -> 실패
ⓑ Dto에 걸려있는 Validation에 문제가 있나 싶어 @NotBlank를 @NotEmpty로, @Size(min = 4, max = 10)을 @Min(4), @Max(10)으로 바꿔 실행해 봄 -> 실패 -> 다시 이전으로 돌려둠
ⓒ Controller에서 Validation에 관한 예외 처리에 대한 내용 상에 return 값을 넣어주니 해결됨!
-> 예외 처리 상에 return 값을 넣어주지 않아 발생한 문제였음
- Validation 중 정규표현식이 제대로 작동하지 않는 문제
* Validation이 모두 동작하는 듯 보였으나 다른 Validation은 제대로 작동했지만 정규표현식이 제대로 작동하지 않는 문제가 발생함
-> https://ko.wikipedia.org/wiki/%EC%A0%95%EA%B7%9C_%ED%91%9C%ED%98%84%EC%8B%9D를 통해 정규 표현식을 공부 후 '@Pattern(regexp = "[A-Za-z0-9]")'로 작성해 두었음
-> 이전에 작성해둔 다른 코드를 참고하여 '@Pattern(regexp = "^[A-Za-z0-9]*$")'로 수정하니 해결됨
POSIX 기본 및 확장 표준의 문법 중 ^ : 처음, $ : 끝, * : 0개 이상 문자 포함
- 로그인 성공 시 Response Body에 Response가 반환되지 않는 문제
* Spring Security를 사용해 로그인에 필터가 걸려있어 Controller 상에서는 Response Body에 Response를 담기가 어려웠음
ⓐ JwtAuthenticationFilter 상에 로그인 성공과 실패시 동작하는 코드 밑에 redirect를 사용하여 Controller에 각각의 사례에 따른 url로 이동하도록 작성해 봄 -> Response Body에 Response를 반환하지만 로그인 성공 시 Postman에서 생성된 토큰이 보이지 않는 문제가 발생함
// 로그인 성공 시
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
String username = ((UserDetailsImpl) authResult.getPrincipal()).getUsername();
String token = jwtUtil.createToken(username);
response.addHeader(JwtUtil.AUTHORIZATION_HEADER, token);
response.sendRedirect("/api/user/login/success");
}
// 로그인 실패 시
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
response.setStatus(401);
response.sendRedirect("/api/user/login/unsuccess");
}
ⓑ 구글링을 통하여 HttpServletResponse에서 Response Body 에 객체를 Json 형태로 담아 반환하는 방법을 찾아 해결함
// 로그인 성공 시
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
String username = ((UserDetailsImpl) authResult.getPrincipal()).getUsername();
String token = jwtUtil.createToken(username);
response.addHeader(JwtUtil.AUTHORIZATION_HEADER, token);
statusResponse(response, "성공");
}
// 로그인 실패 시
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
response.setStatus(401);
statusResponse(response, "실패");
}
// Response Body에 상태 담아 반환하기
private void statusResponse (HttpServletResponse response, String message) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
UserResponseDto responseDto = new UserResponseDto("로그인", message, response.getStatus());
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(responseDto);
response.getWriter().write(result);
}
Next...
- 스프링 숙련 복습 및 개인과제 lv.3 작성
- 알고리즘 공부 및 그룹 스터디
- 자바의 정석 공부 + 자바 문법 종합반 복습