[Spring] Controller

2024. 1. 9. 11:43· 공부/Spring
목차
  1. Spring Boot Request Mapping
  2. Controller
  3. User class 추가하기 - Lombok 사용
  4. WebController 수정
  5. Path Variable
  6. Controller에서 Path Variable 사용하여 보기
  7. Query String
  8. Controller에서 Query String을 받을 수 있도록 추가
  9. View Rendering
  10. RestController
  11. @RequestMapping
  12. Controller, RestController

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 형식으로 반환된다.

Untitled.png

  • @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에 사용된다.

Untitled.png

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

Untitled.png

  • Query는 대부분 선택적인 값으로 사용하므로 다음과 같이 수정한다.
@GetMapping("/hello")
	@ResponseBody
	public String hello(@RequestParam(name="name", required=false, defaultValue="user")String name) {
		return "Hello!!! " + name;
	}
  • default값은 “user” 로 설정되어있고, 필수가 아니도록 수정하였다.

Untitled.png

View Rendering

  • @Controller로 표기된 클래스의 함수 중 @ResponseBody 표기가 없는 함수는 기본적으로 View를 Rendering 하여 응답한다.

Untitled.png

  • 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을 통해 렌더링될 페이지에 전달하는 역할로 사용한다.

Untitled.pngUntitled.png

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 프로그램 사용 가능
  1. Spring Boot Request Mapping
  2. Controller
  3. User class 추가하기 - Lombok 사용
  4. WebController 수정
  5. Path Variable
  6. Controller에서 Path Variable 사용하여 보기
  7. Query String
  8. Controller에서 Query String을 받을 수 있도록 추가
  9. View Rendering
  10. RestController
  11. @RequestMapping
  12. Controller, RestController
'공부/Spring' 카테고리의 다른 글
  • [Spring]JPA 사용해보기
  • [Spring]WAS(Web Application Server)
  • [Spring]개발환경설정
  • [Spring]Spring Framework 소개
Future0_
Future0_
rm -rf /
Future0_
Luna Developer Blog
Future0_
전체
오늘
어제
  • 분류 전체보기 (111)
    • 프로그래밍 (4)
      • 알고리즘 (4)
    • 보안 (14)
      • Dreamhack (4)
      • Hackthebox (1)
      • Webhacking (9)
    • 프로젝트 (4)
    • 공부 (80)
      • Database (2)
      • Python (11)
      • System (4)
      • Java (13)
      • JSP (13)
      • Spring (11)
      • Kotlin (16)
      • 자료구조 (10)
      • 기계학습 (0)
    • Docker (4)
    • Github (2)
    • Tip (0)
    • 잡담 (2)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • api 통신
  • docker
  • 보안
  • dreamhack
  • 코틀린기본문법
  • Android Studio
  • ViewModel
  • 자바빈즈
  • 알고리즘
  • Database
  • native app
  • android studio 삭제
  • 프로그래밍
  • Kotlin
  • Java
  • Python
  • 상속
  • 키 해시
  • webhacking
  • Computer science
  • shared preference
  • React
  • 컴퓨터
  • cs
  • 디버깅키해시
  • 자료구조
  • jsp
  • 1.9.22
  • SpringBoot
  • spring

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.0
Future0_
[Spring] Controller
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.