[Spring] 스프링 입문 스프링부트 (2) (업데이트중)

jeonghyun·2023년 3월 20일
0

정적 컨텐츠

정적 컨텐츠는 파일 그대로를 보여주는 것이다.
resources/static/@.html -> localhost:8080/@.html로 접속하면 해당 파일을 볼 수 있다.

  • hello-static.html 생성(resources/static/hello-static.html)
  • 실행
  • localhost:8080/hello-static.html 접속

MVC와 템플릿 엔진

MVC : Model, View, Controller
Controller에 parameter를 추가하였다.(@RequestParam(name="name)String name)

  • parameter : url에서 localhost:8080/hello-mvc?name=aaa -> name=aaa 뜻함

★ @RequestParam의 구성
@RequestParam([name =] "가져올 데이터의 이름") [데이터 타입][가져온 데이터를 담을 변수])
name이라는 파라미터의 값을 name에 저장한다.

  • controller
    - HelloController.java에 작성
    @GetMapping("hello-mvc")
     public String helloMvc(@RequestParam(value = "name"[,required=true])String name, Model model){
         model.addAttribute("name", name);
         return "hello-template";
     }
     ```
     
     * required의 default: true이다.(localhost:8080/hello-mvc
     뒤에 ?name=spring!로 매개변수값 필수로 넘겨줘야한다.)
  • View
    - hello-template.html 생성(resources/template/hello-template.html)
    <html xmlns:th="http://www.thymeleaf.org">
    <body>
    <p th:text="'hello ' + ${name}">hello! empty</p>
    </body>
    </html>```

?name="아무말"이라고 쓰면

이런 결과가 나오게 된다.

API

	@GetMapping("hello-string")
    @ResponseBody  // return값?를 그대로 반영 -> 소스코드 봤을때도 return값만 보임
    public String helloString(@RequestParam("name") String name){
        return "hello " + name;
    }

JSON방식으로

	@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;
        }



    }

0개의 댓글