[Likelion] Spring 스터디 1주차

99winnmin·2022년 7월 8일
0

likelion

목록 보기
1/5
# 1주차 7/6~7/13
강의자료 및 내용 출처 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
목표 : 섹션0,1,2 강의 수강

프로젝트 환경설정

라이브러리 살펴보기

Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 한다.

Gradle을 눌러보면 필요한 라이브러리를 Spring-web과 thymeleaf만 선택했다. 위와 같이 라이브러리들이 어떠한 의존관계를 맺고 있는지 알 수 있는데 Gradle은 이런 의존관계에 있는 라이브러리들을 모두 자동으로 다운로드해준다.

서버 개발자는 로그를 남기는 것이 아주 중요한데 logging과 관련해서 주요한 두 가지 라이브러리이다. 시간이 나면 꼭 검색해보자. 다음은 주요 라이브러리이다.

스프링 부트 라이브러리

  • spring-boot-starter-web
    -spring-boot-starter-tomcat: 톰캣 (웹서버)
    -spring-webmvc: 스프링 웹 MVC
  • spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)
  • spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅
    -spring-boot / spring-core
    -spring-boot-starter-logging / logback, slf4j

테스트 라이브러리
spring-boot-starter-test
junit: 테스트 프레임워크
mockito: 목 라이브러리
assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
spring-test: 스프링 통합 테스트 지원

View 환경설정

프레임워크를 배울 때 공식 사이트에서 기능을 검색하는 것은 매우 중요하다. 해당 url에서 자주 찾아보도록하자

또한 spring-boot의 reference doc도 자주 활용하도록 하자

# Welcome Page
Spring Boot supports both static and templated welcome pages.
It first looks for an index.html file in the configured static content locations. 
If one is not found, it then looks for an index template.
If either is found, it is automatically used as the welcome page of the application.

spring 웹 application을 실행하면 resource/static/index.html을 기본으로 실행한다는 내용이다.

springboot로 url하나 실행해보기

  • HelloController.java
package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","hello!!");
        // resources/templates/hello.html 찾아가는데 "data":"hello!!"를 담아서 감
        return "hello";
    }
}


controller에서 리턴 값으로 문자를 반환하면 viewResolver가 화면을 찾아서 처리한다.

  • spring-boot 템플릿엔지 기본 viewName 매핑(@Controller 어노테이션이 동작하게 하는 것 같다.)
  • viewResolver가 찾는 html 경로 : resources:templates/{viewName}+.html ({viewName}은 return "hello";에서 반환되는 문자열임)

build & execute

CLI환경 이용하기!(로컬 cmd는 윈도우니까 git bash 이용하였음)
1. ./gradlew build -> .jar 파일 생성
2. cd /build/libs
3. java -jar .jar -> 서버를 배포할 때에 .jar파일만 배포하면 된다고 함
4. 실행 확인

spring web 개발 기초

정적 컨텐츠

서버에서 동작없이 웹 브라우저에 그대로 전달하는 것, 페이지 그대로 client에게 전달

1. Spring Container에서 hello-static 이 mapping되는 것이 있는지 먼저 체크!!
2. 없으면 resources:static/hello-static.html을 반환!

MVC와 템플릿 엔진

서버에서 변형 후 html에 값을 전달한 후 client에게 전달되는 방식
view를 찾아서 템플릿 엔진을 통해서 화면을 렌더링해서 웹 브라우저에 넘겨주는 것!
MVC: Model, View, Controller

1. Spring Container에서 hello-template 이 mapping되는 것이 있는지 먼저 체크!!
2. helloController 객체에서 매핑이 되는 메서드가 있음으로 메서드 호출
3. 리턴 값과 모델을 spring의 viewResolver(화면과 관련된 해결자)에게 전달
4. templates/리턴값.html에 값을 매핑시켜서 변환 후 html 전달

  • 예제 코드
	@GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(name = "name",required = false) String name, Model model){
        model.addAttribute("name",name);
        // "name"은 넘어갈 키 값, name은 /hello-mvc/name01과 같이 request로 넘어온 값
        return "hello-template";
    }

API

JSON 데이터 구조로 네트워크 통신으로 데이터를 전달하는 방식

1. Spring Container에서 hello-api가 mapping되는 것이 있는지 먼저 체크!!
2. 매핑이 되는 것이 있는데 @ResponseBody가 붙어있으면 http response body에 그대로 넘겨야되겠구나! 하고 동작함, 근데?! 문자가 아니고 객체가 반환이 되야한다면?
3. 객체를 json 구조로 바꾸고 반환되는 것이 기본 정책
4. viewResolver가 아닌 HttpMessageConverter가 동작하게 되는데 반환값이 String이면 StringConverter가 동작하게되고 객체가 반환되게 되면 JsonConverter가 동작하게됨
-기본 문자처리: StringHttpMessageConverter
-기본 객체처리: MappingJackson2HttpMessageConverter
-byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음
5. 변환 후 json 리턴하게 됨

  • 예제 코드
	@GetMapping("hello-api02")
    @ResponseBody // json으로 반환되는 것이 default로 되어 있음
    public Hello helloApi02(@RequestParam("name") String name){
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }

    static class Hello{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
profile
功在不舍

0개의 댓글