프로젝트 환경설정, 스프링 웹 기초

링딩·2022년 6월 30일
0

스프링 입문

목록 보기
1/2
post-thumbnail

프로젝트 환경설정

1. 프로젝트 생성

프로젝트 생성 사이트



2. 라이브러리 설명

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

스프링 부트 라이브러리

  • 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: 스프링 통합 테스트 지원



3. View 환경설정

3-1. 정적페이지

  • static/index.html 에 올려두면 Welcome 페이지가 제공 됨.


3-2. thymeleaf 템플릿 엔진

@Controller
public class HelloController {

  @GetMapping("hello")
  public String hello(Model model) {
  	model.addAttribute("data", "hello!!");
 	return "hello";
 }
}

<resource/templates/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>
  1. @GetMapping 으로 /hello로 들어오면 이 이름을 가진 Get 매핑타입의 메소드를 찾아서 연결됨
  2. model.addAttribute에서 model 매개변수에 data라는 key를 넘겨준다. (여기서 value="hello!!")
  3. return 값을 통해 /templates/hello.html을 호출해준다.


4. 빌드 및 실행

<윈도우에서 방법 >

  1. 콘솔로 이동 명령 프롬프트(cmd)로 이동
  2. ./gradlew gradlew.bat 를 실행하면 됩니다.
  3. 명령 프롬프트에서 gradlew.bat 를 실행하려면 gradlew 하고 엔터를 치면 됩니다.
    gradlew build



섹션2. 스프링 웹 개발 기초

1. MVC와 템플릿 엔진

요즘엔 Model, View, Controller 이런 식으로 분리를 하는 것이 추세임.

[Controller]

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

[resources/template/hello-template.html]

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

작동과정
1. Controller의 @RequestParam의 'name' 키를 통해 url에서, 직접적으로 name=값 의 형식_으로 model을 통해 값을 전달할 수 있습니다.
=> html의 ${name}에 1번의 model 값이 적용됩니다.



2. API

✨ 요즘 추세임

@ResponseBody 객체 반환

@Controller
public class HelloController {
 	@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를 이용하면 viewResolver 를 사용하지 x
    • 객체 반환시 -> JSON으로 변환
    • 문자를 처리하냐 객체를 처리하냐에 따라 Converter가 달라짐
    • 기본 문자처리: StringHttpMessageConverter
    • 기본 객체처리: MappingJackson2HttpMessageConverter
profile
초짜 백엔드 개린이

0개의 댓글