Tag 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 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

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 »

Spring 5 에 ehcache 2 적용 샘플

By | 4월 9, 2020

1.  pom.xml <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <!– Spring 혹은 Terasoluna 에 최신버전이 내장되어 있어서 버전을 지정하지 않았었음. 아마 2.10.x 버전인듯 –> </dependency>   2. ehcache.xml <?xml version=”1.0″ encoding=”UTF-8″?> <ehcache xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”http://ehcache.org/ehcache.xsd” updateCheck=”false”> <!– * 속성 설명 (출처: https://javacan.tistory.com/entry/133) – maxElementsInMemory: 메모리에 저장될 수 있는 객체의 최대 개수 (필수) – eternal: 이 값이 true이면 timeout 관련 설정은… Read More »

Spring 파일 다운로드(file download)시 사용하는 View 샘플 코드

By | 9월 5, 2019

* View 정의 /** * 파일 다운로드시 Controller 에서 return 할 목적으로 생성한 view * * @author STEVE */ @Slf4j @Component(“fileDownloadView”) public class FileDownloadView extends AbstractView { private FileInputStream fin = null; private BufferedInputStream bis = null; private ServletOutputStream sout = null; private BufferedOutputStream bos = null; @SuppressWarnings(“rawtypes”) @Override protected void renderMergedOutputModel(Map params, HttpServletRequest request,… Read More »