Category Archives: Spring

[spring] 파일 다운로드 컨트롤러 샘플 (file download, ResponseEntity)

By | 1월 5, 2024

환경 spring 4.3.25 import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import java.nio.file.Files; … @Controller public class FileController { @GetMapping("/download") public ResponseEntity<byte[]> download(HttpServletRequest request, Model model){ // TODO: 필요할 경우 여기에 권한 검증 로직 추가 // 아래의 값들은 DB조회 등을 통해 가져온다고 가정 String fileFullPath = "blabla~"; // file physical full path String oriFileName =… Read More »

[spring] jsp > jstl 에서 spring bean 에 접근하는 방법

By | 12월 19, 2023

테스트 환경 spring 4 포인트 jsp에서 접근하고자 하는 spring bean을 view resolver 에서 expose 해 준다. 샘플 코드 (spring) dispatcher-servlet.xml > InternalResourceViewResolver, TilesViewResolver 등에서 아래와 같은 형식으로 property를 set 해 준다. <property name="exposedContextBeanNames"> <list> <value>[jsp에서 접근하기 원하는 bean name]</value> </list> </property> 샘플 코드 (jsp) <c:set var="[변수명]" value="${[bean name]}" scope="application" /> 소감 application scope에 데이터를 셋팅하기… Read More »

[spring] 프로퍼티 파일 (*.properties) 의 내용을 정적 멤버(static member field)에 할당하는 방법 (feat. @Value)

By | 12월 5, 2023

방법 1 @Value 를 field가 아닌 static setter method 에 붙이기. => component 초기화 시 자동으로 setter가 호출된다고 한다. @Component public class MyBean { private static String staticProperty; @Value("${my.property}") private void setStaticProperty(String myProperty) { MyBean.staticProperty = myProperty; } public static String getStaticProperty() { return staticProperty; } } 소감 null fallback을 따로 해 주지 않아도 되서… Read More »

Spring 4 에서, controller method argument 로 HttpServletResponse를 추가했을 때, ContentNegotiatingViewResolver 를 통한 json view로의 resolving이 실행되지 않았던 건에 대하여

By | 10월 16, 2023

쓰고 보니 무슨 라노벨 제목처럼 되어 버렸네; 아무튼, 당연히 되어야 하는 json view response가 되지 않아서 한참을 삽질하다가 원인을 파악했다. (response가 argument에 있으면 안됨) 만약 특정 업무에서 response를 반드시 가공해야만 하는 경우가 생긴다면, 이미 만들어 둔 custom json view 에 분기코드를 심는 것이 좋을 것 같다. (controller 에서 model.addAttribute를 통해 분기 플래그 셋팅하는 등) gpt의… Read More »

[spring] WebMvcConfigurer > addInterceptors > excludePathPatterns 의 wildcard(*, asterisk) 문법에 대하여 (url 패턴에 의한 권한체크 필터)

By | 4월 27, 2023

예시 // 작동함 .excludePathPatterns("/aaa/**") .excludePathPatterns("/bbb*/**") // 작동하지 않음 .excludePathPatterns("/aaa**") // 별표 두개는 꼭 슬래쉬 뒤에 와야 하는 것 같다. 순서에 대하여 gpt에 물어보니, 패턴을 정의하는 순서에 의미가 있다고 한다. (위의 것이 먼저 필터링) 실험 결과 넓은 url 범위를 exclude 하고, 하위의 좁은 범위를 다시 add 했을 때, add가 의도한대록 작동(권한체크)되지는 않았다. (gpt는 된다고 했는데…?)

spring web 에서 파라미터를 전송할 때, 아무 이유 없이 파라미터 바인딩(parameter, bind, bound)이 되지 않았던 경우 (camel case, jackson)

By | 12월 13, 2022

전달되지 않은 파라미터 명: fInput 전달된 파라미터 명: ffInput ??? 원인 jackson이 java bean naming convention을 사용하는데, java 표준에는 ‘Don’t capitalize first two letters of a bean property name’ 라는 룰이 있다고 한다. 결국 jackson이 json parsing 하는 각 프로퍼티의 첫 두 글자는 무조건 소문자여야 한다는 것. 참고 https://stackoverflow.com/questions/30205006/why-does-jackson-2-not-recognize-the-first-capital-letter-if-the-leading-camel-c http://futuretask.blogspot.com/2005/01/java-tip-6-dont-capitalize-first-two.html

[펌글] SpringDoc (swagger 생성기) 을 노출하지 않기 (운영환경에서 필요할 듯)

By | 7월 4, 2022

Hi, This feature will be added on v1.2.12, of springdoc-openapi. This property helps you disable only the ui. springdoc.swagger-ui.enabled=false The following property, will help you disable the api-docs Rest endpoints as well: springdoc.api-docs.enabled=false 출처 https://github.com/springdoc/springdoc-openapi/issues/191

[링크] [java/spring] 쿼리 로그 출력시 파라미터 값이 바인딩된 채로 출력되게 하는 방법 (parameter bound query sql log) – log4jdbc-log4j2

By | 6월 23, 2022

https://rimkongs.tistory.com/312 이게 2013년 이후 업데이트가 끊긴 라이브러리라 최근에는 사용할 수 없을 거라고 막연히 생각했었는데, 웬걸, 2022년 지금도 잘 돌아가고 있는 모양이다. 괜히 p6spy 쓴다고 낑낑댄 건 아닌지 모르겠다. 심지어 이넘은 쿼리 결과도 테이블 모양으로 이쁘게 찍어준다.

spring boot jar 실행시 mybatis typeAlias 관련 오류 해결 (SpringBootVFS)

By | 4월 13, 2022

환경 springboot 2.6.3 mybatis-spring-boot-starter 2.2.2 mybatis 설정파일에 typeAlias 를 정의해 사용하고 있음. 서버 기동(springboot jar 파일 실행)시 에러메시지 org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias ‘[VO클래스명]’. Cause: java.lang.ClassNotFoundException: Cannot find class: [VO클래스명] 이 에러는 spring boot를 jar로 packaging하여 실행하는 경우에만 발생한다고 함. 해결 (xml config) 나는 설정의 편의를 위해 java config가… Read More »

org.apache.xerces.jaxp.SAXParserFactoryImpl cannot be cast to javax.xml.parsers.SAXParserFactory 오류 해결

By | 12월 10, 2021

환경 spring boot 1.5.22 (spring 4.3.25) JEUS 7 Fix#5 개요 잘 돌던 시스템이, apache poi를 pom에 추가한 시점부터 JEUS 서버 기동시 오류를 내뿜었다. (주로 logback.xml 을 읽지 못했다… 라는 내용의 로그였음) 해결 pom.xml > dependency > poi-ooxml 에 아래와 같이 exclusion 처리 추가 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> <exclusions> <exclusion> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> </exclusion> </exclusions> </dependency> 출처… Read More »

springboot 환경설정 메모 (ver 1.5.22)

By | 9월 23, 2021

web환경 (servlet..)을 제거하는 설정 application.yml spring: main: web-environment: false spring security 를 제거하는 설정 기동 클래스 @SpringBootApplication(exclude = { SecurityAutoConfiguration.class }) application.yml security: basic: enabled: false management: security: enabled: false

Spring @Scheduled 스케쥴러 사용 샘플 (cron 표현식 등)

By | 8월 11, 2021

Spring Boot 라면 @EnableScheduling 을 붙여서 기본 셋팅이 가능한 것 같은데, 일반 Spring 에서는 아래와 같은 셋팅을 추가해 주어야 한다. thread pooling 관련 설정을 하기도 하는 것 같은데, 여기서는 가장 심플한 구성을 사용하기로 한다. spring context xml (‘task’ 가 포인트) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!–… Read More »

json 출력 혹은 swagger 문서에서 VO객체의 일부 필드(멤버) 숨기기 (Spring 4, jackson2, springfox 2.9 환경)

By | 6월 30, 2021

@ApiModelProperty(notes = "책 썸네일 atchFileId", hidden = true) @JsonIgnore private String bookThumbnailFileId; swagger의 모델 정의에서 필드 숨기기 @ApiModelProperty를 아예 필드에 붙이지 않는다. 모종의 이유로 붙였을 경우에는 @ApiModelProperty(hidden = true)를 사용한다. json response 에서 필드 숨기기 @JsonIgnore 를 사용한다. @JsonIgnore는 꼭 com.fasterxml.jackson.annotation.JsonIgnore 을 사용해야 한다. (java 패키지 확인)

[펌글] Spring Security 에서의 CORS 설정

By | 6월 29, 2021

spring security config 클래스 @EnableWebSecurity public class CustomSecurityConfig extends WebSecurityConfigurerAdapter { … @Override protected void configure(HttpSecurity http) throws Exception { http … .and() .authorizeRequests() .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() // cors setting 1 … .and().cors(); // cors setting 2 } // cors setting 3 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // configuration.addAllowedOrigin("*"); configuration.addAllowedOrigin("http://localhost:3000"); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*");… Read More »

Spring 4 JUnit 테스트 샘플 코드 (Spring 4.3.16 기준, Spring boot 예제 아님)

By | 6월 14, 2021

pom.xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.16</version> </dependency> TestJUnit.java package twopro; // 테스트코드에서도 log4j를 사용하고 싶다면 패키지는 꼭 필요한 듯. import cmm.jwt.TokenProvider; import lombok.extern.slf4j.Slf4j; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; /** * JUnit 테스트 * * @author 이프로 * @version 2021.06… Read More »

Spring 에서 @ResponseBody 로 json serialized response(응답) 를 생성할 때의 json 변환 규칙 재정의 하기 (null => “” 변환 등…)

By | 2월 11, 2022

일단 Spring 4에 내장된 jackson2 를 그대로 활용한다는 가정하에 기술한다. NullSerializer 작성 import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; /** * jackson > Object의 null값을 "null" 문자열 대신 ""로 출력할 수 있도록 설정 */ public class NullSerializer extends JsonSerializer<Object> { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException… Read More »