Backend/spring (Boot) 26

Connection Pool과 Size 선정 기준 (with HikariCP)

🔍 1. 커넥션 풀(Connection Pool)이란?데이터베이스와 연결(Connection)을 미리 만들어 풀(Pool)에 보관해두고, 요청이 들어오면 즉시 꺼내서 사용하고 다시 반납하는 구조. ✅ 장점매번 DB 연결을 새로 만들지 않아도 돼서 속도 빠름DB 커넥션 수를 제한해 과부하 방지 🔍 2. HikariCP란?Spring Boot의 기본 커넥션 풀 구현체.빠르고 가벼운 커넥션 풀로, 성능이 뛰어나서 널리 쓰인다.📌 3. HikariCP 설정✅ 3-0. yaml 예시spring: datasource: hikari: maximum-pool-size: 30 minimum-idle: 30 idle-timeout: 60000 connection-timeo..

[Spring, JSP] session 생성 차단

jwt 방식 로그인을 사용하기 때문에 세션을 생성하지 않도록 Spring Security 에서 아래와 같이 설정했다.근데도 JSESSIONID가 생기고 있었다. 나는 jsp를 사용하는게 문제였다!!📌 1. 목적: 완전한 무상태(Stateless) 서버 만들기Spring Security에서 SessionCreationPolicy.STATELESS를 설정JWT 기반 인증이나 토큰 기반 인증을 쓸 때는 세션이 필요 없으므로, JSESSIONID 쿠키도 없어야 정상.http .cors(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session .sessionCreation..

[Spring] (프로젝트 외부) 정적 리소스 처리

📌0. 서블릿 컨테이너 기본 동작 자원이 프로젝트 내부 /resources 또는 /static 밑에 있을 때✅ 0-1. Spring MVC (레거시 설정, xml 기반)DispatcherServlet을 /에 매핑하면 모든 요청이 DispatcherServlet으로 감.정적 리소스도 DispatcherServlet을 거치게 됨 → 그래서 Spring이 ResourceHttpRequestHandler를 통해 다시 정적 리소스 처리를 해줘야 함.✅ 0-2. Spring Boot 동작 원리스프링부트는 자동으로 ResourceHandlerRegistry를 등록해서, 별도 mvc:resources를 안 써도 정적 리소스 핸들러가 붙음.기본 매핑 경로:classpath:/static/classpath:/public..

Spring boot 예외 처리: @ControllerAdvice, @ExceptionHandler, ResponseStatusException

기존에 controller에서 예외 catch해서 직접 처리하는 방식을 자주 사용했었다.@GetMapping("/user/{id}")public ResponseEntity getUser(@PathVariable Long id) { try { User user = userService.findById(id); return ResponseEntity.ok(new ApiResponse("SUCCESS", "조회 성공", user)); } catch (UserNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ApiResponse("FAIL..

[error] java.lang.IllegalArgumentException: Name for argument of type [int] not specified

🚨 Name for argument of type [int] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag. java.lang.IllegalArgumentException: Name for argument of type [int] not specified Ensure that the compiler uses the '-parameters' flag. This application has no explicit mapping for /error, so you are seeing this as a fallback.Wed Fe..

[error] getOutputStream() has already been called for this response

🚨 Could not write JSON: getOutputStream() has already been called for this response  🔥 오류 원인HttpServletResponse의 getOutputStream() 또는 getWriter()가 여러 번 호출되었을 때 발생하는 문제!즉, 응답을 한 번 보낸 후에 또 응답을 보내려고 할 때 발생한다.  📖 에러 코드 (수정 전) ➡️ 쿠키를 response.addCookie()로 설정한 후, ResponseEntity로 JSON 응답을 반환. ➡️ 하지만 ResponseEntity가 HTTP 응답을 설정하는 과정에서 response.getOutputStream()을 다시 호출하기 때문에 충돌이 발생. @PostMapping("/l..

[JAVA] 쿠키(Cookie) 설정 방법

쿠키 설정 방법에 대해 알아보기전에 쿠키에 대해 간단히 알아보자!!🔍 쿠키(Cookie)란? 쿠키는 웹 브라우저에 저장되는 작은 데이터 조각!!서버가 클라이언트(브라우저)에 정보를 저장하고, 이후 요청에서 다시 전송하도록 도와주는 역할➡️ 쿠키는 웹에서 사용자 상태를 유지하는 중요한 메커니즘! 🍪 🚀 특징세션 유지: 로그인 상태 유지, 장바구니 정보 저장클라이언트 저장: 브라우저에 텍스트 형태로 저장됨자동 전송: 동일한 도메인에 대한 요청마다 자동 포함🎯 쿠키 설정 시 추가할 내용✅ HttpOnly → 자바스크립트에서 접근 불가능하게 해서 보안 강화✅ Secure → HTTPS에서만 쿠키 전송 (HTTPS 환경이라면 꼭 설정!)✅ Path=/ → 모든 경로에서 쿠키 사용 가능✅ Max-Age / ..

[Spring Security] CSRF & CORS 개념 및 설정 방법

📌 1. CSRF(Cross-Site Request Forgery)란?사용자가 로그인된 상태에서 악성 사이트를 통해 원치 않는 요청을 보내도록 유도하는 공격 방식예를 들어, 사용자가 은행 웹사이트에 로그인한 상태에서 악성 스크립트가 계좌이체 요청을 보내면 공격이 성공할 수 있음 ✅ 1-1. Spring Security에서 CSRF 설정 방법🔹 CSRF 방어 활성화 (기본값)Spring Security에서는 CSRF 보호가 기본적으로 활성화됨폼 기반 로그인(formLogin())을 사용할 때 CSRF 방어가 필요함@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http ..

[error] conversionServicePostProcessor Bean 중복 오류

🚨 conversionServicePostProcessor Bean 중복 오류 A bean with that name has already been defined in class path resource Description: The bean 'conversionServicePostProcessor', defined in class path resource [org/springframework/security/config/annotation/web/reactive/WebFluxSecurityConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [or..

[Spring Security] Web vs WebFlux Spring Security 설정

📌 Spring Security 설정 방법 비교Spring Security 설정 방식은 Spring MVC(Web)와 Spring WebFlux에서 차이가 있다!! 🚀아래에서 클래스 차이, 필터 적용 방식, UserDetailsService 사용 방식을 비교해보자. 😊 🔥 Spring MVC vs WebFlux 차이 요약 Spring MVC (Web)Spring WebFluxSecurity 설정 클래스@EnableWebSecurity@EnableWebFluxSecurityFilterChain 타입SecurityFilterChainSecurityWebFilterChain요청 인증 설정authorizeHttpRequests()authorizeExchange()필터 추가 방식addFilterBefore..