스프링 입문 - 1.웹 개발 기초

dy7888·2023년 1월 12일
0
post-thumbnail



1. 정적 컨텐츠

정적 컨텐츠는 파일을 그대로 웹 브라우저에 전송한다.

  1. http://localhost:8080/hello-static.html에 접속
  2. 내장 톰캣 서버가 받아서 스프링에 넘김
  3. 스프링이 hello-static 컨트롤러를 찾지만 존재하지 않음
  4. 내부에 있는 static/hello-static.html 반환


2. MVC

  • Model, View, Contoller. View는 화면을 생성하는데 집중
  • Contoller와 Model은 비즈니스 모델과 같이 내부적인 부분을 처리


Controller

@Controller 
public class HelloController {
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template"; // hello-template.html을 리턴
    }
}
  • 링크에 /hello-mvc?name=spring 출력: hello spring
  • @RequestParam()은 Spring 이런식으로 값을 직접 전달받지 않고 외부에서 파라미터 받을때 사용
  • Ctrl+P로 옵션 알 수 있음
  • model.addAttribute("name", name)은 파라미터로 넘어온 값을 name이라는 key와 함께 모델에 담는다. 모델은 View에서 렌더링할때 사용


View

<html xmlns:th="http://www.thymeleaf.org">
<body> 
<p th:text="'hello ' + ${name}">hello! empty</p>
<!--${  } : model의 key값이 name인 것을 꺼내서 치환해줌-->
</body>
</html>


3. MVC 동작 원리


1. 웹브라우저에서 http://localhost:8080/hello-mvc?name=spring 접속하여 톰캣에게 보낸다.
2. 스프링은 helloController의 메서드에 hello-mvc로 Mapping이 되어 있으니 호출한다.
3. hello-template으로 리턴하고, 모델에 키는 "name", 값은 'spring!'을 넣어 전달한다.
4. hello-template으로 return을 했기 때문에, viewResolver가 templates/hello-template.html을 찾아 thymeleaf 템플릿 엔진으로 처리하도록 한다.
5. 템플릿 엔진이 렌더링을 해 변환을 한 HTML을 전달한다.



4. API

  • 문자 반환 : html 태그 없이 문자 그대로 반환하는 방식이나 잘 사용하지 않음

  • 객체 반환 : @ResponseBody 를 사용하여 객체를 반환하면 객체가 JSON형식으로 변환됨

 @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello(); // Hello라는 객체 생성해서 hello라는 변수에 넣어줌
        hello.setName(name);
        return hello; // 객체 리턴
    }


⭐ 단축키 정리

  • Alt+Shift+Enter : 자동완성
  • Alt + Insert : getter setter같은 필요한 옵션 단축키
profile
나의 기록하는 개발 일지

0개의 댓글