상세 컨텐츠

본문 제목

Spring 웹 개발 기본 원리

Spring

by aeongiii 2024. 11. 30. 20:58

본문

웹 브라우저에서 http://localhost:8080/hello-spring.html 호출할 경우

→ 내장 톰캣 서버를 거쳐 스프링부트로 들어온다.

(1) 컨트롤러에서 찾는다. hello-spring이라는 컨트롤러가 있는가? ⇒ mvc방식 또는 api 방식

(2) resources 폴더에서 찾는다. hello-spring.html 파일이 있는가? ⇒ 정적 컨텐츠 방식

 

 

 

1. 정적 컨텐츠

 

2. MVC와 템플릿 엔진

    • 템플릿 엔진을 모델, 뷰, 컨트롤러 방식으로 쪼갠다.
    • @RequestParam이 붙어있다.
      • name을 받아서 model에 저장한다. model(name:spring)
      • return값인 “hello-template”에 맞는 템플릿을 찾는다.
      • view의 ${name} 부분에 주입한다.
    • http://localhost:8080/hello-mvc?name=spring 호출해보면 “hello” + name이 같이 출력된 것을 볼 수 있다.
@Controller
public class HelloController {

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

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

 

3. API 방식

  • @ResponseBody 를 사용하면 HttpMessageConverter가 동작한다.
  • 문자 내용을 HTTP Response에 넣어서 그대로 반환한다. (뷰 없이)
  • HttpMessageConverter의 동작 방식
    1. 컨트롤러 메서드에서 그냥 String을 반환하는 경우, StringConverter가 동작한다.
    @Controller
    public class HelloController {
    
    	@GetMapping("hello-string")
    	**@ResponseBody**
    	public String helloString(@RequestParam("name") String name) {
    		return "hello " + name;
    	}
    }
    ==> 문자 그대로를 반환한다.
    
    1. 객체를 반환하는 경우, JsonConverter가 동작한다.
    @Controller
    public class HelloController {
    
    	@GetMapping("hello-api")
    	@ResponseBody
    	public Hello helloApi(@RequestParam("name") String name) { 
    		Hello hello = new Hello();
    		hello.setName(name);
    		return hello;                  ===> Hello 객체를 반환하고 있다.
    	}
    	
    	static class Hello {
    	
    		private String name;
    		
    		public String getName() {
    		return name;
    		}
    		
    		public void setName(String name) {
    		this.name = name;
    		}
    	}
    }                                     
    

관련글 더보기