[Spring] 스프링 입문하기 (2) - 스프링 웹 개발 기초

함은지·2022년 4월 6일
0

Spring

목록 보기
2/4

이번 포스팅에서는 스프링 웹 개발 기초의 세 단계를 정리하려고 한다.

정적 콘텐츠

  • resource/static 폴더에 html을 입력한 것을 그대로 웹으로 보여준다
  • resource/static에 "hello-static.html" 파일을 생성하고 다음 소스코드를 입력하고 실행해보자.
<!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"을 입력하면 된다.

    localhost:8080/hello-static.html

정직하게 실행된 것을 알 수 있다.

  • 소스코드를 보면 다음과 같다.

  • 소스코드 보기에서 알 수 있듯이 정적 콘텐츠는 resource/static에 작성한 html 파일을 그대로 보여주는 것이다.
  • 실무에서는 거의 사용하지 않으니 참고만 하자.




MVC와 템플릿 엔진

  • MVC는 Model, View, Controller의 약자다.
  • 이 방식은 정적 콘텐츠 방식과 다르게 컨트롤러를 이용한다.
  1. src/main/java/hello.hellospring에 "controller" 폴더를 생성한다
  2. "controller" 폴더에서 "HelloController" 클래스를 생성한다.
  3. 다음 소스코드를 입력한다.
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";
    }
}
  • helloMvc가 호출되면 "hello-template"를 리턴하는데 이는 src/main/resources/template에서 찾는다.
  1. src/main/resources/template에서 "hello-template.html" 파일을 생성한다.
  2. 다음 소스코드를 입력하고 실행한다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • 크롬에 다음과 같이 입력하여 실행해보자.
  • 앞서 실행했던 방법과 마찬가지로 "localhost:8080" 뒤에 "hello-mvc"를 추가하면 된다.

    localhost:8080/hello-mvc

  • 오류가 발생했다! Intellij 로그를 살펴보자.

  • 잘 살펴보면 다음과 같은 경고창이 뜬다.

    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]

  • 오류가 발생한 이유는 name 파라미터에 어떤 값도 넘겨주지 않았기 때문이다.
  • 크롬에 다음과 같이 입력하여 name에 "spring"을 넘겨줘보자.

    localhost:8080/hello-mvc?name=spring

  • helloMvc의 name에 상기와 같은 방법으로 스트링을 넘겨줄 수 있다.
  • 결과 화면에는 "hello "+ name 이 출력되도록 되어있는데 name="spring"을 입력했더니 spring이 출력된 것을 알 수 있다.
  • 소스코드 보기를 하면 다음과 같다.

  • 앞서 방식과는 다르게 컨트롤러와 html을 이용해서 웹 페이지를 만들 수 있다.
  • html이 그대로 출력되는 것이 아니라 MVC를 이용해 데이터를 넘길 수 있다.




API

스트링 반환

  • API 방식은 앞서 사용한 방법과 다르게 html 파일을 사용하지 않는다.
  • "@ResponseBody"를 이용해 html을 넘기는 것이 아니라 데이터를 그대로 넘긴다.
  • 무슨 말인지는 직접 해보자!
  • 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

  • name에 "spring"이라는 데이터를 넘겨주고 실행했더니 위와 같이 출력되었다.
  • 소스코드를 봐보자.

  • html이 아닌 데이터가 직접 입력된 것을 알 수 있다.
  • @ResponseBody는 html을 이용하지 않고 데이터를 직접 웹 페이지에 출력해준다.

객체 반환

  • 이번에는 객체를 반환하는 방식을 사용해보자.
  • 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;
        }
    }
  • Hello 클래스에 name을 private로 선언하고 getter와 setter를 생성했다.
  • 앞서 했던 방식대로 다음과 같이 실행할 수 있다.

    localhost:8080/hello-api?name=spring

  • helloApi는 Hello 객체를 반환하는데 다음과 같이 JSON 형태로 출력되는 것을 알 수 있다.
  • JSON은 {"key":"value"} 형태로 데이터를 처리한다.
  • 앞서 두 방식과 다르게 html을 사용하지 않으며 스트링이 아닌 JSON 형태로 데이터가 출력된다.



Intellj를 이용해 자동으로 getter,setter를 생성하는 방법

  • Intellij를 이용해 getter와 setter를 쉽게 생성할 수 있다.
  1. 클래스에 attribute를 선언한 후 마우스 우클릭애서 "Generate"를 선택한다.

  1. Getter and Setter를 선택한다.

  1. Ok를 누른다.

  1. 결과 확인. getter와 setter가 자동으로 생성된 것을 알 수 있다.

profile
꾸준히 노력하고 성장하는 개발자

0개의 댓글

관련 채용 정보