스프링 프로젝트 초기 환경

구름코딩·2020년 10월 14일
0

프로젝트 빌드 도구

  • Maven Project
  • Gradle Project (대부분 사용)
    • Gradle이 버전 설정 및 필요한 라이브러리를 가져온다
    • 내가 필요한 라이브러리만 체크하더라도 해당 라이브러리와 의존성 관계가 있는 라이브러리를 모두 가져온다

프로젝트 디렉토리 구성

src 폴더 (main, test 폴더 존재)

  • main내부에 java파일만을 담는 java폴더와 그외 파일들을 담는 resources 폴더가 존재
  • test내부에는 테스트를 위한 java파일이 들어있는 java폴더가 존재

build.gradle 파일

  • 과거에는 일일이 입력하거나 복사해와야 했다
  • spring boot가 나오면서 편리해졌다

spring-boot Library 설명

스프링 부트 라이브러리

  • 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 : 스프링 통합 테스트 지원
spring-boot-stater-logging
  • spring boot 사용시 기본적으로 포함된다
  • logback과 slf4j를 조합으로 이용을 많이 해서 자동으로 묶여서 라이브러리를 제공 (거의 표준)
  • 프로젝트 빌드시 sout이 아닌 log를 통해서 값의 상태를 확인하게 된다
  • logback을 이용하여 출력되며 인터페이스는 slf4j로 구현된다

spring-boot-starter-test
  • junit을 이용하여 테스트를 진행하고 assertj, mockito는 좀더 편리하게 할수 있게 도와주는 라이브러리
  • spring-test은 스프링과 통합해서 테스트를 진행할 수 있도록 해준다

View 환경설정

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 boot 문서

  • index.html 파일 생성
<!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>

스프링 부트가 제공하는 Welcome Page기능

  • static/index.html을 올려두면 Welcome page기능을 제공한다

Template Engines

Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs

Thymeleaf 템플릿 엔진

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development. thymeleaf

여러 도구, 플러그인, 스프링 프레임워크 등과 같이 HTML5 JVM 웹개발에 사용하기에 좋은 서버 자바 템플릿 엔진이다

예시

@Controller 파일

@Controller
public class HelloController {

    //GetMapping은 해당 이름과 메소드를 매핑해주는 것
    @GetMapping("hello") <-- 웹 애플리케이션에서 슬롯(URL)이 hello라고 들어오면 아래 메소드를 호출해준다
    //스프링이 Model형 객체를 만들어서 hello메소드에 넣어서 실행해준다
    public String hello(Model model)
    {
        model.addAttribute("data", "hello!"); <-- 첫번째 인자가 Key, 두번째 인자가 Value로 작동한다, html에서 key값을 넣어서 value값으로 치환하여 출력하는 형태
        return "hello"; <-- 해당 반환값을 이용하여 HTML파일을 찾는다
    }
}
  • GetMapping은 해당 이름과 메소드를 매핑해주는 것
  • MVC(Model View Controller)에서 Model이 위 Model이다
  • 반환값 "hello"를 이용해서 HTML파일을 찾을 때 뷰 리졸버(viewResolver)가 기본적으로 resources/templates/에서 찾는다
    • 스프링 부트 템플릿 엔진 기본 viewName 매핑
    • resources:templates/+{viewName}+.html
    • viewName을 반환값(hello)로 치환하여 찾는다

HTML

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"> <head>  <!--템플릿 엔진으로 thymeleaf를 사용을 명시-->
    <title>Hello</title> <!--브라우저 탭 이름-->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p> <!--data가 key로서 불려진 메소드의 model.addAttribute를 통해 들어간 value값을 가져와서 치환된다-->
</body>
</html>

spring-boot-devtools라이브러리를 추가하면, html파일만 컴파일해서 서버 재시작 없이 View파일 변경이 가능하다, build -> Recompile

구현된 모습

profile
내꿈은 숲속의잠자는공주

0개의 댓글