Jin's Dev Story

[SpringBoot] 에러 처리 본문

Web & Android/SpringBoot

[SpringBoot] 에러 처리

woojin._. 2023. 10. 14. 10:02

4xx - 클라이언트 에러

5xx - 서버 에러

 

1) pom.xml 파일에서 Unknown 에러 없애기

  • <properties>안에 <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>을 추가(프로퍼티 버전 설정을 추가)
  • 그리고 나서, 프로젝트 선택 후 마우스 오른쪽 클릭 → [Maven] → [Update Project …] 선택

2) 생성한 프로젝트에 빨간 느낌표 뜨는 경우

  • 프로젝트 우클릭 → Properies → Libraries → JRE System Library 버전 변경
    • 내 경우엔 디폴트 JRE로 변경해주니 에러가 사라짐

3) java.lang.UnsupportedClassVersionError

  • Eclipse run 시 발생
  • JRE를 1.8로 변경하니 해결됨

4) 스프링부트 Whitelabel Error Page 에러

5) 시큐리티 적용 안됨(관리자, 일반)

  • springsecurity5 로 적용 후 Securityconfig에 hasRole(”ADMIN”)으로 관리자만 접근할 수 있게 설정했음 → 오류는 안뜨는데 시큐리티 적용이 되지 않는 문제점 발생
  • 해결 방법
    • springsecurity6 으로 변경 후 버전 6에 맞도록 스프링부트 설정하니 해결 됨
 

스프링 부트 2.0에서 3.0 스프링 시큐리티 마이그레이션 (변경점)

목차 스프링 부트 3.0 부터 스프링 시큐리티 6.0.0 이상의 버전이 적용되었습니다. 스프링 부트 2.7.8 까지는 deprecated는 되었더라도 기존 설정대로 대부분 사용 가능했으나, 스프링 부트 3.0 부터는

nahwasa.com

 

스프링부트 3.0이상 Spring Security 기본 세팅 (스프링 시큐리티)

목차 [수정 사항] 2023-03-29 : 커스텀 어노테이션 적용하는 부분에서 소스코드에 잘못 들어간 코드가 있어서 삭제 1. 시작하기 전에 1.1 설정 이해 보다는 당장 시큐리티 설정 복붙이 필요한 분들에

nahwasa.com

6) 이미지 수정이 안됨

indexoutofboundsexception: index 0 out of bounds for length 0] with root cause

  • itemService.java에서 이미지 수정 시 아래와 같은 문장이 실행되도록 함 → 그러나 itemImgIds.get(i)에서 해당 오류가 발생(log.info로 찍어보니 값이 0이 나옴 → List에 값이 없어서 오류가 발생함)
// 이미지 수정
        for (int i = 0; i < itemImgFileList.size(); i++) {
            itemImgService.updateItemImg(itemImgIds.get(i), itemImgFileList.get(i));
        }
  • 해결 방법
    • itemForm.html에서 타임리프의 값을 가져오기 위한 name 속성 값과 itemFormDto.java에서 사용하는 리스트의 변수명을 동일하게 변경
<input type="hidden" name="itemImgIds" th:value="${itemImgDto.id}">
private List<Long> itemImgIds = new ArrayList<>(); // 이미지들에 대한 번호 관리

7) 메인 페이지 이미지 뜨지 않는 오류

  • 해결 방법 → WebMvcConfig.java에 @Configuration 를 설정하지 않았음

8) $.ajax is not a function 에러

  • 상품 상세 이미지에서 주문하기 버튼 클릭 시 주문이 완료되었다는 alert 창이 떠야하는데 안뜨고 해당 에러 발생
    • layout1.html에 jquery 설정이 문제였음
    • jquery-3.6.1.slim.min.js 로 설정해놨는데 여기서 slim을 제외하고 jquery-3.6.1.min.js 으로 변경해야하는데 뒤에 integrity로 보안 설정을 추가로 해놔서 slim을 빼버리면 에러가 없어지지 않았음
    • 그래서 integrity를 삭제 후 확인해보니 에러 해결!
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<!--<script src="https://code.jquery.com/jquery-3.6.1.slim.min.js" integrity="sha256-w8CvhFs7iHNVUtnSP0YKEg00p9Ih13rlL9zGqvLdePA=" crossorigin="anonymous"></script>-->

9) org.springframework.data.mapping.PropertyReferenceException: No property 컬럼명 found for type Entity명! Did you mean 'Entity에_있는_컬럼명'?

 

JPA No Property 메소드명 found 에러 해결방법

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 컬럼명 found for type Entity명! Did you mean 'Entity에_있는_컬럼명'? JPA에서 Repository 단에 신규 메소드를 추가할 경우 No Property 메소드명 fou

wakestand.tistory.com

10) Argument [30] of type [java.lang.Long] did not match parameter type [kr.spring.item.entity.Item (n/a)]]

  • 구매 이력 부분에서 오류 남
  • OrderService와 itemImgRepository.findByItemAndRepimgYn()에서 타입 오류 발생
// ItemImgRepository
ItemImg findByItemAndRepimgYn(Long itemId, String repimgYn);

//=> 수정
ItemImg findByItemAndRepimgYn(Item item, String repimgYn);
// OrderService
// 주문 목록 조회
    @Transactional(readOnly = true)
    public Page<OrderHistDto> getOrderList(String email, Pageable pageable) {

        List<Order> orders = orderRepository.findOrders(email, pageable);
        Long totalCount = orderRepository.countOrder(email);

        List<OrderHistDto> orderHistDtos = new ArrayList<>();

        for(Order order : orders) {
            OrderHistDto orderHistDto = new OrderHistDto(order);
            List<OrderItem> orderItems = order.getOrderItems();
            for(OrderItem orderItem : orderItems) {
                ItemImg itemImg = itemImgRepository.findByItemAndRepimgYn(orderItem.getItem().getId(), "Y");
                OrderItemDto orderItemDto = new OrderItemDto(orderItem, itemImg.getImgUrl());
                orderHistDto.addOrderItemDto(orderItemDto);
            }
            orderHistDtos.add(orderHistDto);
        }
        return new PageImpl<OrderHistDto>(orderHistDtos, pageable, totalCount);
    }

// => 수정
// 주문 목록 조회
    @Transactional(readOnly = true)
    public Page<OrderHistDto> getOrderList(String email, Pageable pageable) {

        List<Order> orders = orderRepository.findOrders(email, pageable);
        Long totalCount = orderRepository.countOrder(email);

        List<OrderHistDto> orderHistDtos = new ArrayList<>();

        for(Order order : orders) {
            OrderHistDto orderHistDto = new OrderHistDto(order);
            List<OrderItem> orderItems = order.getOrderItems();
            for(OrderItem orderItem : orderItems) {
                ItemImg itemImg = itemImgRepository.findByItemAndRepimgYn(orderItem.getItem(), "Y");
                OrderItemDto orderItemDto = new OrderItemDto(orderItem, itemImg.getImgUrl());
                orderHistDto.addOrderItemDto(orderItemDto);
            }
            orderHistDtos.add(orderHistDto);
        }
        return new PageImpl<OrderHistDto>(orderHistDtos, pageable, totalCount);
    }

11) 갑자기 모든 클래스에 오류가 생김

 

[Spring] Cannot resolve symbol 'springframework'

오랜만에 Springboot로 작업한 프로젝에 들어갔더니 관련 키워드에 다 빨간줄이 그어져 있었다. \*\*\* 다른 블로그의 화면이지만 마치 이렇게 보였다.빨간 키워드에 뜨는 경고문으로 서칭을 하였다

velog.io

  • 3번째 방법으로 해결

첫번째 방법

빌드를 다시 한다.상단 메뉴바 Build > Clean Project 하고 나서, Build > Rebuild Project(이 방법은 해보지 않았다.)

두번째 방법

캐시를 비우고 재실행한다.상단 메뉴바 File > Invalidate Cashes / Restart.. 선택IDE가 재실행하고 확인을 한다.(이 방법으로는 해결되지 않았다.)

세번째 방법

Gradle을 refresh 해준다.상단 메뉴바 View > Tool Windows > Gradle에 들어간다.우측에 새로운 윈도우가 생성된다. 여기서 프로젝트명을 우클릭하여 Refresh Gradle Dependencies를 누르고 기다린다.(이 방법으로 해결되었다.)

네번째 방법

Preferences (cmd + ,)에서Build, Execution, Deployment > Build Tools > Gradle > Build and Run using과 Run tests using이 Gradle이라면 Intellij IDEA로 바꿔준다.(원래 설정이 되어있었다.)

다섯번째 방법

IDE를 최신버전으로 업데이트한다.

12) 로그인 후 whitelabel error 발생

 

스프링부트 Whitelabel Error Page 에러 해결방법

프로제트 서버를 실행 한 후 localhost:8080 으로 접속을 해보면 Whitelabel Error Page 에러가 발생하는 경우가 있는데 전체 에러 메시지는 아래와 같다 Whitelabel Error Page This application has no explicit mapping for

wakestand.tistory.com

  • 해결 방법
    1. 스프링 구동 시 처음에는 무조건 index.html 을 찾게 설정이 되어있기 때문에index.html을 만들어두지 않으면 이런 에러가 난다.
      • resources - static - index.html 생성
    2. .requestMatchers(”/error”).permitAll() 추가

13) no matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.1.3 was found.

  • JDK 버전 문제
  • 17로 맞추어놨는데도 해결 X
  • 해결 방법
    • 인델리제이 gradle 설정 해야함
    • File - Setting - Build, Ex…, Build Tools, Gradle → Gradle JVM : 17로 설정

14) Security 버전 변경됨으로 config에서 오류 발생

 

Allow CORS with Spring Security 6.1.1 with authenticated requests

I've upgraded from Spring Boot 2.5 to 3.1, which comes with Spring Security 6.1.1. Calls to the login authentication REST service work just fine, but all requests to other REST controllers that req...

stackoverflow.com

  • 해결 전
package com.example.walkingmate_back.login.config;

import com.example.walkingmate_back.login.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@Configuration // 설정파일 선언
@EnableWebSecurity // security사용 선언
@RequiredArgsConstructor
public class AuthenticationConfig {

    // @EnableWebSecurity를 선언함으로 써 모든 api 요청을 security가 관리하게 됨.
    private final LoginService loginService;

    @Value("${jwt.secret}")
    private String secretKey;

    // api 요청이 들어오면 검사하는 security의 FilterChain설정.
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
								.httpBasic().disable()
                .csrf().disable()
                .cors().and()
                .authorizeHttpRequests()
                .requestMatchers("/api/login", "/api/join", "/buyHistory/**", "/board/**", "/user/**", "/battle/**", "/checkList/**", "/run/**", "/team/**").permitAll() // 인증 필요없음
                .requestMatchers(HttpMethod.POST, "/api/**").authenticated() // 인증 있어야함   
//                .requestMatchers(HttpMethod.POST, "/api/v1/home/user").hasRole("USER") // USER 권한 있어야함
//                .requestMatchers(HttpMethod.POST, "/api/v1/home/admin").hasRole("ADMIN") // ADMIN 권한 있어야함
	               .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt 사용하는 경우 사용
                .and()
                .addFilterBefore(new JwtFilter(loginService, secretKey), UsernamePasswordAuthenticationFilter.class) // FilterChain 앞에 JwtFilter 추가
                .build();
    }
}
  • 해결 후
package com.example.walkingmate_back.login.config;

import com.example.walkingmate_back.login.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@Configuration // 설정파일 선언
@EnableWebSecurity // security사용 선언
@RequiredArgsConstructor
public class AuthenticationConfig {

    // @EnableWebSecurity를 선언함으로 써 모든 api 요청을 security가 관리하게 됨.
    private final LoginService loginService;

    @Value("${jwt.secret}")
    private String secretKey;

    // api 요청이 들어오면 검사하는 security의 FilterChain설정.
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity

                .csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(request -> request
                        .requestMatchers("/api/login", "/api/join", "/buyHistory/**", "/board/**", "/user/**", "/battle/**", "/checkList/**", "/run/**", "/team/**").permitAll() // 인증 필요없음
                        .requestMatchers(HttpMethod.POST, "/api/**").authenticated() // 인증 있어야함
                )
//                .requestMatchers(HttpMethod.POST, "/api/v1/home/user").hasRole("USER") // USER 권한 있어야함
//                .requestMatchers(HttpMethod.POST, "/api/v1/home/admin").hasRole("ADMIN") // ADMIN 권한 있어야함
                .sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(new JwtFilter(loginService, secretKey), UsernamePasswordAuthenticationFilter.class) // FilterChain 앞에 JwtFilter 추가
                .build();
    }

'Web & Android > SpringBoot' 카테고리의 다른 글

[SpringBoot] 환경 설정  (0) 2023.10.15
[SpringBoot] 한글 변환(\u~)  (0) 2023.10.14
[SpringBoot] @Annotation  (1) 2023.10.14
[SpringBoot] 페이징 처리  (0) 2023.10.14
[SpringBoot] ResponseEntity  (0) 2023.10.14