본문 바로가기

WINK-(Web & App)/Spring Boot 스터디

spring Boot 스터디 1주차 조현상

반응형

개발 환경 설정은

intellij , java11 , spring start io로 세팅하였다.

 

환경 설정이 다 되었는 지 체크하는 방법은 src -> main -> java -> hellospring -> HelloSpringApplication 파일에서 run 시켜주면 된다.

 

문제 없이 run이 된다면 http://localhost:8000 주소로 들어가면 성공이다.

 

웹 개발 방법은 정적 컨텐츠 , MVC와 템플릿 , API 3가지 방법이 있다.

 

우선 첫 번째로 정적 컨텐츠 방법은

src  -> main -> resources -> static 에 들어가서 html을 작성하는 것이다.

기본적으로 스프링은 index.html을 기본경로? 로 세팅이 되어있기 때문에 index.html 을 작성하면

http://localhost:8000 에 접속했을 때 해당 index.html이 뜬다.

 

두 번째로는 mvc 와 템플릿을 이용한 방법이다.

우선 src -> main -> java -> hellospring 디렉토리에 controller 디렉토리를 만들고 

mvc 중 c를 하기 위한 HelloController 이름의 class를 만들어줬다.

@GetMapping("hello")
public String hello(Model model){
    model.addAttribute("data", "hello!");
    return "hello";
}

그리고 위 코드와 같이 작성하게 되는데

코드를 해석해보자면

@GetMapping("hello")

는 http://localhost:8000/hello 로 접속하면 화면을 보여준다는 것을 의미한다.

model.addAttribute("data", "hello!");
return "hello";

return 이 의미하는 것은

src  -> main -> resources -> templates 로 가서 hello.html 과 연결? 을 한다는 것을 의미하고

addAttribute 는 hello.html 에 있는 key 가 data 인 것을 hello! 로 바꾼다는 것을 의미한다.

그래서 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'안녕하세요.' + ${data}">안녕하세요 손님</p>
</body>
</html>

hello.html 에서 <p th:text="'안녕하세요.' + ${data}">안녕하세요 손님</p> 보면은 data 가 hello!로 바껴서 화면에 출력되는 것을 볼 수 있다.

 

마지막으로 api 형태는 mvc 와 동일하게 controller 에서 작성이 되는데 

@GetMapping("hello-string")
@ResponseBody
public String hellostring(@RequestParam("name") String name){
    return "hello" + name ;
}

 

mvc와 다른 점은 @ResponseBody 가 추가되었다는 점이다.

 @ResponseBody를 쓰면 html에 접근하지 않고 바로 화면에 출력해줄 수 있다.

그래서 위 코드를 입력하고 http://localhost:8000/hello-string?name=1234 로 들어가면

hello1234 가 출력되는 것을 볼 수 있다.

 

api 개발 형태는 두 가지 서로 다른 방법이 있는데

우선 첫 번째는 방금과 같이 hello1234 처럼 string 타입을 출력하는 방법이 있고

두 번째는 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;
        }


    }

return 타입을 객체로 class를 만들어주면 json 형태로 바뀌어서 출력이 되는데

http://localhost:8000/hello-string?name=spring 이라고 주소를 입력하면

{name:spring} 으로 json 형태가 출력되는 것을 볼 수 있다.

반응형