본문 바로가기
Back/Spring

[Spring] 스프링 웹 개발 기초

by 오엥?은 2023. 4. 27.
반응형

 

프로젝트 생성

 

  • 인텔리제이에서 advanced > build.gradle 파일을 연 후, 실행시키고 http://localhost:8080/ 을 확인한다.

이 화면 뜨면 성공

 

  • 설정 > gradle 입력 > Build and run using, Run tests using 을 intelliJ IDEA로 바꾸기

 

 

 

정적 컨텐츠

  • 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
  • http://localhost:8080/hello-static.html 에 들어가보면 그대로 출력된 것을 볼 수 있다.

 

 

MVC 와 템플릿 엔진

  • MVC : Model, View, Controller

- hello-template.html 을 작성하고,

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

- HelloController 에 아래와 같이 작성한다.

@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
    model.addAttribute("name", name);

    return "hello-template";
}

이러면 에러가 난다.

왜냐면 왜냐면

바로

바로

Required request parameter 'name' for method parameter type String is not present

파라미터 'name' 이 없기 때문이다.

 

그럼 해결법은 'required = false' 를 적어주면 된다.

@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(value = "name", required = false) String name, Model model) {
    model.addAttribute("name", name);

    return "hello-template";
}

그리고 주소

localhost:8080/hello-mvc 뒤에 '?name=' 하여 값을 전달해 주면 된다.

그럼 에러 안 나고 잘 뜬다.

 

 

 

API

 

@ResponseBody 

 :  http는 head와 body로 나뉜다. ResponseBody 를 쓰면, body에 return 값을 직접 넣겠다는 뜻이다.

@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam(value = "name", required = false) String name) {
    return "hello " + name;
}
 

이 경우는 view가 필요가 없다.

봐라 html 없어도 그냥 출력

 

문자가 아닌 데이터를 내놓으라고 한다면?

static class 를 만들어서 그 안에 name의 Getter, Setter를 만들어주고 (프로퍼티 접근방식), 위의 HelloApi 에서는 문자가 아닌 객체를 반환한다.

그리고 실행시켜보면 갑작스럽게 중괄호가 생긴 것을 볼 수 있다. 저런 형태로 화면에 출력된다.

반응형