목차
Controller
Spring Boot Request Mapping
- Request의 정보(url, method)를 기반으로 이를 처리할 함수(Controller)로 연결해 주는 것
- 다른 WAS 에서는 Routing 이라는 표현도 사용한다.
- Request로 전달되는 주요 정보
- url : 서버 정보 이후의 주소 : /users, /posts
- method : GET, POST, PUT, PATCH, DELETE 등
- path parameter : 주소의 일부를 식별자로 사용 /users/123 /posts/111
- query string : url 뒤에 ? 를 이용해 전달되는 추가 정보, 정보, 검색어 등
- /users?orderBy=birthYear /users?name=홍길동
Controller는 Request를 처리할 객체
Controller
- Request를 처리할 객체, 프로젝트 패키지 내에 생성한다.
- 클래스 이름은 자유, Annotation으로 Controller 클래스임을 알린다.
- Controller
- View 또는 json string으로 response 할 수 있는 Controller 클래스
- 주로 UI를 그릴 수 있는 view를 response 하는데 사용한다.
- RestController ← backend API를 구성할 때 주로 사용
- json string을 response 할 수 있는 Controller 클래스
- UI 없는 Back-end를 작성하려면 이 클래스가 좀 더 편하다.
Controller와 RestController 두 개 동시 사용 가능
User class 추가하기 - Lombok 사용
- Controller 기능 테스트를 위해 프로젝트에 User class를 추가한다.
package com.example.패키지이름;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@AllArgsConstructor
@Getter
public class User {
private int id;
private String name;
}
- @AllArgsConstructor 모든 property를 반드시 입력받는 생성자를 추가한다. 이 경우 모든 변수는 final 로 처리되어 Getter 만 가질 수 있다.
- @RequiredArgsConstructor
- @NonNull 로 표기된 property만 입력받는 생성자를 추가한다.
- @NonArgsConstructor 아무 인자도 받지 않는 생성자를 추가한다.
AllArgsConstructor를 적으면 굳이 final을 적지 않아도 자동적으로 값을 변경할 수 없도록 됨
WebController 수정
package com.example.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebController {
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/hello")
@ResponseBody
public User hello() {
return new User(1, "ABC");
}
}
- /hello 에 GET 요청을 해보면 객체가 JSON string 형식으로 반환된다.
- @Controller 로 정의된 경우 @ResponseBody 가 추가로 정의되면 Return 되는 객체를 Json String으로 변환하여 Response 된다.
Path Variable
- 주소의 일부분을 식별자로 사용하는 것. 하나의 객체로 표시되는 정보를 대상으로 할 때 사용한다.
- 예
- https://20180320.tistory.com/66
- 사용자 아이디 게시글 아이디
Controller에서 Path Variable 사용하여 보기
@GetMapping("/hello/{id}")
@ResponseBody
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
- /hello 로 요청이 들어오면 User 객체에 1, “ABC”의 값이 들어가지만, /hello/??? 의 값이 들어오면 User 객체가 만들어 질때 요청이 들어온 id값을 id에 사용된다.
Query String
- 식별자가 아닌 데이터에 주로 사용. 리스트로 반환되는 결과를 대상으로 한다.
- 검색어, 정렬, 페이징 등
- Path Variable 과 달리 해당 값이 전달되지 않을 수도 있기 때문에 이를 처리해야 되는걸 염두해 두어야함
- 예
- 값이 하나만 있을 때
- https://section.blog.naver.com/OfficialBlog.naver?currentPage=1
- 값을 여러 개 사용할 때, “이름=값&이름=값” 형식
- https://search.shopping.naver.com/search/all?query=귤&cat_id=&frm=NVSHATC
- 값이 하나만 있을 때
Controller에서 Query String을 받을 수 있도록 추가
@GetMapping("/hello")
@ResopnseBody
public String hello(@RequestParam(name="name")String name) {
return "Hello!!! " + name;
}
- Query는 대부분 선택적인 값으로 사용하므로 다음과 같이 수정한다.
@GetMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name="name", required=false, defaultValue="user")String name) {
return "Hello!!! " + name;
}
- default값은 “user” 로 설정되어있고, 필수가 아니도록 수정하였다.
View Rendering
- @Controller로 표기된 클래스의 함수 중 @ResponseBody 표기가 없는 함수는 기본적으로 View를 Rendering 하여 응답한다.
- Thymeleaf 엔진은 확장자로 html을 사용한다.
- resources/tmplates 폴더에 form.html, result.html 추가
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form</title>
</head>
<body>
<form action="/processForm" method="post">
<input type="number" name="id" placeholder="아이디를 입력하세요">
<input type="text" name="name" placeholder"이름을 입력하세요">
<input type="submit" value="확인">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>result</title>
</head>
<body>
<p th:text="${id}"></p>
<p th:text="${name}"></p>
</body>
</html>
Controller
@GetMapping("/form")
public String form() {
return "form";
}
@PostMapping("/processForm")
public String processForm(
@RequestParam("id") int id,
@RequestParam("name") String name,
Model model) {
model.addAttribute("id", id);
model.addAttribute("name", name);
return "result";
}
- @RequestParam
- Form 의 input
- 이 이름
- Model
- View로 전달할 데이터
- addAttribute로 데이터 추가
UI에서
를 렌더링해야 하니까 Model을 사용함
추 후 DB에서 쿼리의 결과문을 Model을 통해 렌더링될 페이지에 전달하는 역할로 사용한다.
RestController
- Json string으로 객체 정보를 response 할 때는 @ResponseBody 를 매번 추가하는 것이 귀찮음
- @RestController로 정의된 클래스에서는 @ResponseBody 없이 바로 사용 가능
- 프로젝트에 ‘ApiController” 클래스 추가 및 기존 (View)Controller에서 @ResponseBody를 가져와서 어노테이션을 지우고 사용한다.
package com.example.spring;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@GetMapping("/hello")
public User hello(@RequestParam(name = "name", required = false, defaultValue = "user") String name) {
return new User(1, name);
}
@GetMapping("/hello/{id}")
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
- @RestController의 각 함수는 객체를 반환해야 한다.
@RequestMapping
- 모든 함수가 공통적인 주소로 시작할 경우 그 주소에 대한 모든 요청을 한꺼번에 받을수도 있다.
@RestController
@RequestMapping("/hello")
public class ApiController {
@GetMapping("") // "/hello"
public User hello(@RequestParam(name = "name", required = false, defaultValue = "user") String name) {
return new User(1, name);
}
@GetMapping("/{id}") // "/hello/{id}"
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
}
- @RequestMapping 은 모든 Method에 대해 Controller 지정
Controller, RestController
- WAS에서 Webpage 를 제공하는 경우
- Controller : Web page 를 제공
- RestController: Web page 에서 axios 등을 통해 전송되는 Request 처리
- React, Vue, 모바일 등의 Client 를 별도 개발하는 경우
- RestController 만 구현해도 가능.
- 테스트를 위해서는 Postman, Insomnia 등의 http client 프로그램 사용 가능
Controller
Spring Boot Request Mapping
- Request의 정보(url, method)를 기반으로 이를 처리할 함수(Controller)로 연결해 주는 것
- 다른 WAS 에서는 Routing 이라는 표현도 사용한다.
- Request로 전달되는 주요 정보
- url : 서버 정보 이후의 주소 : /users, /posts
- method : GET, POST, PUT, PATCH, DELETE 등
- path parameter : 주소의 일부를 식별자로 사용 /users/123 /posts/111
- query string : url 뒤에 ? 를 이용해 전달되는 추가 정보, 정보, 검색어 등
- /users?orderBy=birthYear /users?name=홍길동
Controller는 Request를 처리할 객체
Controller
- Request를 처리할 객체, 프로젝트 패키지 내에 생성한다.
- 클래스 이름은 자유, Annotation으로 Controller 클래스임을 알린다.
- Controller
- View 또는 json string으로 response 할 수 있는 Controller 클래스
- 주로 UI를 그릴 수 있는 view를 response 하는데 사용한다.
- RestController ← backend API를 구성할 때 주로 사용
- json string을 response 할 수 있는 Controller 클래스
- UI 없는 Back-end를 작성하려면 이 클래스가 좀 더 편하다.
Controller와 RestController 두 개 동시 사용 가능
User class 추가하기 - Lombok 사용
- Controller 기능 테스트를 위해 프로젝트에 User class를 추가한다.
package com.example.패키지이름;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@AllArgsConstructor
@Getter
public class User {
private int id;
private String name;
}
- @AllArgsConstructor 모든 property를 반드시 입력받는 생성자를 추가한다. 이 경우 모든 변수는 final 로 처리되어 Getter 만 가질 수 있다.
- @RequiredArgsConstructor
- @NonNull 로 표기된 property만 입력받는 생성자를 추가한다.
- @NonArgsConstructor 아무 인자도 받지 않는 생성자를 추가한다.
AllArgsConstructor를 적으면 굳이 final을 적지 않아도 자동적으로 값을 변경할 수 없도록 됨
WebController 수정
package com.example.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebController {
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/hello")
@ResponseBody
public User hello() {
return new User(1, "ABC");
}
}
- /hello 에 GET 요청을 해보면 객체가 JSON string 형식으로 반환된다.
- @Controller 로 정의된 경우 @ResponseBody 가 추가로 정의되면 Return 되는 객체를 Json String으로 변환하여 Response 된다.
Path Variable
- 주소의 일부분을 식별자로 사용하는 것. 하나의 객체로 표시되는 정보를 대상으로 할 때 사용한다.
- 예
- https://20180320.tistory.com/66
- 사용자 아이디 게시글 아이디
Controller에서 Path Variable 사용하여 보기
@GetMapping("/hello/{id}")
@ResponseBody
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
- /hello 로 요청이 들어오면 User 객체에 1, “ABC”의 값이 들어가지만, /hello/??? 의 값이 들어오면 User 객체가 만들어 질때 요청이 들어온 id값을 id에 사용된다.
Query String
- 식별자가 아닌 데이터에 주로 사용. 리스트로 반환되는 결과를 대상으로 한다.
- 검색어, 정렬, 페이징 등
- Path Variable 과 달리 해당 값이 전달되지 않을 수도 있기 때문에 이를 처리해야 되는걸 염두해 두어야함
- 예
- 값이 하나만 있을 때
- https://section.blog.naver.com/OfficialBlog.naver?currentPage=1
- 값을 여러 개 사용할 때, “이름=값&이름=값” 형식
- https://search.shopping.naver.com/search/all?query=귤&cat_id=&frm=NVSHATC
- 값이 하나만 있을 때
Controller에서 Query String을 받을 수 있도록 추가
@GetMapping("/hello")
@ResopnseBody
public String hello(@RequestParam(name="name")String name) {
return "Hello!!! " + name;
}
- Query는 대부분 선택적인 값으로 사용하므로 다음과 같이 수정한다.
@GetMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name="name", required=false, defaultValue="user")String name) {
return "Hello!!! " + name;
}
- default값은 “user” 로 설정되어있고, 필수가 아니도록 수정하였다.
View Rendering
- @Controller로 표기된 클래스의 함수 중 @ResponseBody 표기가 없는 함수는 기본적으로 View를 Rendering 하여 응답한다.
- Thymeleaf 엔진은 확장자로 html을 사용한다.
- resources/tmplates 폴더에 form.html, result.html 추가
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form</title>
</head>
<body>
<form action="/processForm" method="post">
<input type="number" name="id" placeholder="아이디를 입력하세요">
<input type="text" name="name" placeholder"이름을 입력하세요">
<input type="submit" value="확인">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>result</title>
</head>
<body>
<p th:text="${id}"></p>
<p th:text="${name}"></p>
</body>
</html>
Controller
@GetMapping("/form")
public String form() {
return "form";
}
@PostMapping("/processForm")
public String processForm(
@RequestParam("id") int id,
@RequestParam("name") String name,
Model model) {
model.addAttribute("id", id);
model.addAttribute("name", name);
return "result";
}
- @RequestParam
- Form 의 input
- 이 이름
- Model
- View로 전달할 데이터
- addAttribute로 데이터 추가
UI에서
를 렌더링해야 하니까 Model을 사용함
추 후 DB에서 쿼리의 결과문을 Model을 통해 렌더링될 페이지에 전달하는 역할로 사용한다.
RestController
- Json string으로 객체 정보를 response 할 때는 @ResponseBody 를 매번 추가하는 것이 귀찮음
- @RestController로 정의된 클래스에서는 @ResponseBody 없이 바로 사용 가능
- 프로젝트에 ‘ApiController” 클래스 추가 및 기존 (View)Controller에서 @ResponseBody를 가져와서 어노테이션을 지우고 사용한다.
package com.example.spring;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@GetMapping("/hello")
public User hello(@RequestParam(name = "name", required = false, defaultValue = "user") String name) {
return new User(1, name);
}
@GetMapping("/hello/{id}")
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
- @RestController의 각 함수는 객체를 반환해야 한다.
@RequestMapping
- 모든 함수가 공통적인 주소로 시작할 경우 그 주소에 대한 모든 요청을 한꺼번에 받을수도 있다.
@RestController
@RequestMapping("/hello")
public class ApiController {
@GetMapping("") // "/hello"
public User hello(@RequestParam(name = "name", required = false, defaultValue = "user") String name) {
return new User(1, name);
}
@GetMapping("/{id}") // "/hello/{id}"
public User hello(@PathVariable("id") int id) {
return new User(id, "ABC");
}
}
- @RequestMapping 은 모든 Method에 대해 Controller 지정
Controller, RestController
- WAS에서 Webpage 를 제공하는 경우
- Controller : Web page 를 제공
- RestController: Web page 에서 axios 등을 통해 전송되는 Request 처리
- React, Vue, 모바일 등의 Client 를 별도 개발하는 경우
- RestController 만 구현해도 가능.
- 테스트를 위해서는 Postman, Insomnia 등의 http client 프로그램 사용 가능