Post

[KT AIVLE] Spring 5일차 - 심화학습

0. 개요


오늘은 Spring Boot 실습을 위주로 진행되었습니다.


1. Spring Boot


1: Bootstrap

  • Bootstrap 소개
    • CSS 라이브러리로, 반응형 웹사이트를 빠르게 개발 가능.
    • Bootstrap 공식 사이트에서 다운로드 및 사용법 확인 가능.
  • 컴포넌트 및 레이아웃
    • 그리드 시스템: 12 컬럼 기반 반응형 레이아웃.
    • Content와 Form: 다양한 입력 필드와 유효성 검사 제공.
    • Component: 버튼, 모달, 네비게이션 바 등 UI 요소 지원.
  • 프로젝트 적용
    • header.mustache와 footer.mustache를 생성하여 템플릿 구조화.

2: 뉴스 작성하기 (Create)

  • Form 데이터 처리
    • <form> 태그를 사용하여 데이터를 전송하고, DTO 객체로 수신:
    1
    2
    3
    4
    5
    
    @PostMapping("/news")
    public String createNews(NewsDto.Post post) {
        System.out.println(post.toString());
        return "redirect:/news";
    }
    
  • DTO(Data Transfer Object)
    • 클라이언트 데이터 그룹화:
    1
    2
    3
    4
    
    public static class NewsDto {
        private String title;
        private String content;
    }
    
  • Entity 변환 및 저장
    • DTO를 Entity로 변환 후 데이터베이스 저장:
    1
    2
    3
    
    public static News toEntity(NewsDto.Post post) {
        return new News(null, post.getTitle(), post.getContent());
    }
    

3: H2 데이터베이스로 데이터 조회

  • H2 설정
    • application.yml에 H2 데이터베이스 연결:
    1
    2
    3
    4
    5
    6
    7
    8
    
    spring:
      datasource:
        url: jdbc:h2:~/test
        username: sa
        password: 1234
      h2:
        console:
          enabled: true
    
  • 데이터베이스 확인
    • 브라우저에서 H2 Console 접속 (http://localhost:8080/h2-console) 후 SQL로 데이터 조회.

4: 게시물 읽기 및 전체 조회

  • 전체 게시물 조회
    • 컨트롤러 메서드:
    1
    2
    3
    4
    5
    6
    
    @GetMapping("news")
    public String getAllNews(Model model) {
        List<News> newsList = newsRepository.findAll();
        model.addAttribute("newsList", newsList);
        return "news/list";
    }
    
  • 뷰 페이지 생성
    • list.mustache 파일:
    1
    2
    3
    4
    5
    
      
    {{#newsList}}
      <li>{{title}} - {{content}}</li>
    {{/newsList}}
      
    

5: AppConfig 및 페이징

  • AppConfig
    • 기본 페이징 설정:
      1
      2
      3
      4
      5
      6
      7
      
      @Configuration
      public class AppConfig {
        @Bean
        public PageableHandlerMethodArgumentResolverCustomizer customize() {
            return resolver -> resolver.setMaxPageSize(10);
        }
      }
      
  • 페이징 처리
    • Pageable로 페이지 단위 데이터 조회:
      1
      2
      3
      4
      5
      6
      
      @GetMapping("/news")
      public String getAllNews(Pageable pageable, Model model) {
        Page<News> page = newsRepository.findAll(pageable);
        model.addAttribute("page", page);
        return "news/list";
      }
      


3. 후기


오늘은 주로 Spring Boot의 구조 및 다양한 패턴과 실제 사용방법을 위주로 학습을 진행하였습니다.

다양한 오류 발생시 대처하는 방법을 익힐 수 있었습니다!

This post is licensed under CC BY 4.0 by the author.