이번 포스팅에서는 스프링 웹 개발 기초의 세 단계를 정리하려고 한다.
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
localhost:8080/hello-static.html
정직하게 실행된 것을 알 수 있다.
- src/main/java/hello.hellospring에 "controller" 폴더를 생성한다
- "controller" 폴더에서 "HelloController" 클래스를 생성한다.
- 다음 소스코드를 입력한다.
package hello.hellospring.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", "spring!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
model.addAttribute("name", name);
return "hello-template";
}
}
- src/main/resources/template에서 "hello-template.html" 파일을 생성한다.
- 다음 소스코드를 입력하고 실행한다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
localhost:8080/hello-mvc
2022-04-06 22:12:56.727 WARN 3305 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]
localhost:8080/hello-mvc?name=spring
- src/main/java/hello.hellospring/Controller/HelloController에 다음 소스코드를 추가하자.
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
return "hello " + name;
}
localhost:8080/hello-string?name=spring
- src/main/java/hello.hellospring/Controller/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;
}
}
localhost:8080/hello-api?name=spring
- 클래스에 attribute를 선언한 후 마우스 우클릭애서 "Generate"를 선택한다.
- Getter and Setter를 선택한다.
- Ok를 누른다.
- 결과 확인. getter와 setter가 자동으로 생성된 것을 알 수 있다.