스프링 파일 생성 사이트
https://start.spring.io/
Dependency
는 Thymeleaf, Spring Web
추가
이후 GENERATE
를 통해 파일 생성후 인텔리제이에서 Open
기본 실행은 HelloSpringApplication.java를 실행시켜주면 된다.
package hello.hello_spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloSpringApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringApplication.class, args);
}
}
HelloSpringApplication.class
클래스를 SpringApplication.run
에 넣으면SpringBoot
의 애플리케이션이 실행이 되는 원리이다.localhost:8080
에 들어가게 되면 웹사이트가 뜨게 된다.그러면 다음과 같은 에러 창이 뜨는데 이렇게 뜨면 성공이다.
과정
Spring Boot
는 기본적으로 Tomcat
이라는 내장 웹 서버를 포함하고 있다.Tomcat 실행
: HTTP
요청을 처리할 준비를 한다.포트 바인딩
: 8080포트
에 바인딩되며, 애플리케이션이 해당 포트에서 HTTP 요청
을 받을 준비를 한다.resources/static/index.html
파일을 만들어주면<!DOCTYPE>
<html lang="ko">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
thymeleaf
템플릿 엔진을 쓰면 루프를 바꾸거나 모양을 변경할 수 있다.package hello.hello_spring.Controller;
import org.springframework.context.annotation.ComponentScan;
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
@ComponentScan
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; //html 태그 하나 없이 문자 그대로 웹에 띄어준다. "hello string"
}
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
Hello hello = new Hello();
hello.setName(name);
return hello; //문자가 아닌 객체를 넘겼다. json 방식
}
static class Hello{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
}
@Controller
애노테이션은 스프링 MVC
에서 컨트롤러 클래스
를 명시할 수 있다.@GetMapping(“hello”)
부분이 클라이언트 요청을 받는 부분이고 따라서 웹에서 접속시 localhost:8080/hello
로 들어가야한다. model.addAttribute
에서 data
가 hello.html
에서 ${data}
에 들어갈 부분HelloController
에서 매핑이 되고 hello
라는 메서드가 실행된다. return hello;
을 반환해주고viewResolver
가 템플릿에 hello.html
실행시키게 된다.resources: templates/ + {viewName} + .html
hello.html
에서 HelloControler
에 model
에서 넘어온 키값이 ${data}
에 들어가게 된다../gradlew build
실행그러면 위와같이 bulid
파일이 생성된다.
libs
폴더 들어가기 build
파일에 들어가게되면 libs
라는 파일이 보일 것이다.hello-spring-0.0.1-SNAPSHOT.jar
라 는 이름을 가진 파일이 보일 것이다.java -jar hello-spring-0.0.1-SNAPSHOT.jar(파일명)
를 실행hello-spring-0.0.1-SNAPSHOT.jar
파일만 복사해서 java -jar
를 실행하면 된다.