2021-09-10-TIL
Java
LocalDate, LocalTime, LocalDateTime
Java 8의 java.time 패키지에서 타임존이 없는 날짜와 시간을 표현하는 세 클래스다. LocalDate는 날짜(2021-09-10), LocalTime은 시간(13:45:30), LocalDateTime은 둘을 합친 값이다. 셋 다 불변이고 스레드 안전해서, 값을 바꾸는 메서드(plusDays, withHour 등)는 항상 새 객체를 돌려준다.
이름의 Local은 “어느 지역의 벽시계에 적힌 값”이라는 뜻에 가깝다. 타임존 정보가 없으므로 그 자체로는 시간선 위의 한 순간을 가리키지 못한다. 생일이나 영업 시작 시각처럼 타임존과 무관한 값에는 잘 맞고, 서로 다른 지역 사이의 시각 비교가 필요하면 ZonedDateTime이나 Instant로 바꿔야 한다.
1
2
3
LocalDate date = LocalDate.of(2021, 9, 10);
LocalDateTime dt = date.atTime(9, 0); // 2021-09-10T09:00
LocalDateTime next = dt.plusDays(1); // dt는 그대로, 새 객체 반환
- https://www.daleseo.com/java8-local-date-time/
SpringBoot
Encoding
Spring Boot는 HTTP 요청과 응답의 문자 인코딩을 server.servlet.encoding.* 속성으로 설정한다. 문서에 따르면 charset의 기본값은 UTF-8, enabled는 true다. force는 HttpServletResponse.setContentType 호출에 설정한 charset을 강제로 적용할지 정한다. 응답 한글이 깨질 때는 먼저 이 속성과, 응답 Content-Type에 charset이 실제로 붙어 나가는지를 확인하면 된다.
1
2
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
- https://granger.tistory.com/53
- https://www.python2.net/questions-962693.htm
Gson Unicode
Gson으로 JSON을 만들면 <, >, &, =, ' 같은 문자가 <처럼 유니코드 이스케이프로 바뀌어 나온다. HTML 안에 JSON을 넣을 때 안전하도록 기본으로 HTML 이스케이프를 하기 때문이다. 이 문자를 그대로 내보내려면 GsonBuilder.disableHtmlEscaping()을 쓴다.
1
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
- https://cornswrold.tistory.com/44
RestTemplate request/response logging
RestTemplate의 요청과 응답 본문을 로그로 남기려면 ClientHttpRequestInterceptor를 등록한다. 그런데 응답 본문은 스트림이라 인터셉터에서 한 번 읽으면 이후 메시지 컨버터가 다시 읽을 수 없다. 그래서 BufferingClientHttpRequestFactory로 감싸서 본문을 메모리에 버퍼링한다. Javadoc도 이 팩토리가 응답 본문을 여러 번 읽을 수 있게 해 준다고 설명한다. 대신 큰 응답은 그대로 메모리에 올라가므로 대용량 다운로드에는 맞지 않는다.
1
2
3
RestTemplate restTemplate = new RestTemplate(
new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
restTemplate.getInterceptors().add(new LoggingInterceptor());
- https://www.baeldung.com/spring-resttemplate-logging
Changing Content-type in HTTP header
Spring MVC 핸들러가 어떤 Content-Type으로 응답할지는 @RequestMapping(또는 @GetMapping 등)의 produces 속성으로 정한다. produces는 요청의 Accept 헤더와 협상하는 데 쓰이고, "text/plain;charset=UTF-8"처럼 charset까지 적을 수 있다. 반대로 consumes는 요청의 Content-Type과 맞아야 하는 조건이다.
1
2
@GetMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
public String hello() { return "안녕"; }
- https://stackoverflow.com/questions/19015646/spring-changing-content-type-http-header
댓글
아직 댓글이 없습니다