[기본] Section 01~05 정리

Daily-Log·2024년 4월 16일
0
post-thumbnail

🐢 Section 01. 프로젝트 환경 설정



✨ 01. 프로젝트 생성

1. spring Initializr를 통해 프로젝트 생성

	- 프로젝트 선택
    	- 프로젝트 : Gradle - Groovy
        - Gradle, Maven 이란 : 빌드 관리 도구
        
    - Spring Boot : 2.7.12
        - SNAPSHOT, M1같은 미정식 버전을 제외한 최근 버전으로 선택
        - 3.0 주의
            1. Java 17 이상
            2. javax 패키지 이름을 jakarta로 변경 ( https://bit.ly/springboot3 )
            
    - Language : Java
    
	- Project Metadata    	
    	- Group : hello
    	- Artifact : hello-spring (필자는 전에 만든적 있어서 spring-intro로 변경)
        	- build되어 나온 결과물
    	- Packaging : Jar
    	- Java : 11 (가장 오류 안 나는 버전)

	- Dependencies : Spring Web, Thymeleaf



2. Generate해서 받은 .zip파일을 원하는 폴더 밑에 풀기

  • sync 전
  • sync 후



3. IntelliJ에서 파일 열고 실행

  • 파일을 열면 자동 sync 과정을 진행

  • 아래 버튼을 눌러 실행

  • Tomcat started on port(s): 8080 (http) with context path '' 이 떠야 성공적으로 실행된 것임

  • localhost:8080을 주소창에 입력하면 아래와 같은 페이지가 나타남

  • 만약 Gradle 환경에서 실행했다면, 종료할 때 아래와 같이 오류 문구가 뜸.



✨ 02. 라이브러리 살펴보기

  • Gradle은 의존 관계가 있는 라이브러리를 함께 다운로드 하므로, External Libraries에 보면 수많은 라이브러리들이 존재

  • 아래 화면의 빨간 원 부분을 클릭하면 주황 영역을 없애거나 나타나게 할 수 있음 ( alt 두 번 )

  • Gradle → Dependencies → compileClassPath → starter-web → starter-tomcat 내장
    ⇒ 소스 라이브러리에서 웹 서버를 내장하고 있음

  • 중복되는 의존성이 있는 아이들은 하나만 나타남 (하위에 없다고 해서 의존성 없는 게 X)


📚 핵심 라이브러리

Dependencies 구성

  • compileClasspath
  • runtimeClasspath
  • testCompileClasspath
  • testRuntimeClasspath



스프링 부트 라이브러리

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



테스트 라이브러리

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



✨ 03. View 환경설정

💻 정적 화면

💬 index.html

<!-- 경로 : hello-spring.src.main.resources.static -->
<!DOCTYPE HTML>
<html>
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>




💻 동적 화면

💬 HelloController.java

package hello.springintro.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");
        return "hello";
    }
}

💬 hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

http://localhost:8080/hello



  • 동작 원리
  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리
    - 스프링 부트 템플릿엔진 기본 viewName 매핑
    - resources:templates/ +{ViewName}+ .html


✨ 04. 빌드하고 실행하기

1. gradlew.bat이 존재하는 폴더로 이동
2. gradlew build
3. cd build/libs
4. java -jar hello-spring-0.0.1-SNAPSHOT.jar
5. 실행 확인







🐢 Section 02. 스프링 웹 개발 기초



✨ 01. 정적 컨텐츠

💬 hello-static.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

  • 동작 원리 (Simple)



✨ 02. MVC와 템플릿 엔진

💬 HelloController.java

package hello.springintro.controller;

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

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "hello");
        return "hello";
    }
    
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
}

💬 hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

  • 동작원리



✨ 03. API

💬 HelloController.java

package hello.springintro.controller;

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

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "hello");
        return "hello";
    }
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello"+name;
    }

    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@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;
        }
    }
}

  • 동작원리

  • @ResponseBody 를 사용
    - HTTP의 BODY에 문자 내용을 직접 반환
    - viewResolver 대신에 HttpMessageConverter 가 동작
    - 기본 문자처리: StringHttpMessageConverter
    - 기본 객체처리: MappingJackson2HttpMessageConverter
    - byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

profile
대충 뭐든 먹어요

0개의 댓글

관련 채용 정보