일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- 백준 1504 java
- 익명 객체 @transactional
- spring mongoTemplate switch
- spring mongoTemplate
- nodejs rabbitmq
- javav 1676
- 자바 1676
- spring mongodb switch
- java 1238
- kotiln functional interface
- 백준 연결요소 자바
- java 1509
- 백준 2252 줄세우기
- rabbitmq 싱글톤
- ipfs singletone
- 안정해시
- java 백준 1509
- kotiln const val
- spring mongodb
- Spring ipfs
- 자바 백준 팩토리얼 개수
- kotiln const
- go
- 백준 특정한 최단 경로
- ipfs bean
- java 파티
- 전략 패턴이란
- mongodb lookup
- java 팩토리얼 개수
- Java Call By Refernce
- Today
- Total
공부 흔적남기기
Spring MVC 예제를 통한 이해 본문
코드를 먼저 천천히 살펴보며 이해해보자
package com.sparta.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/hello/request")
public class HelloRequestController {
@GetMapping("/form/html")
public String helloForm() {
return "hello-request-form";
}
// [Request sample]
// GET http://localhost:8080/hello/request/star/BTS/age/28
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=BTS&age=28
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=BTS&age=28
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/model
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=BTS&age=28
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
// Content type: application/json
// Body
// {"name":"BTS","age":"28"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
}
먼저 Mapping 위에 @ResponseBody가 들어간 경우 Response 데이터를 return한다.
그렇지 않고 그냥 return "값" 이 있으면 먼저 타임리프가 templates에 값과 같은 html파일이 있는지 확인하고 있으면 html 값을 리턴한다. 못 찾으면 에러페이지가 나온다.
이제 @ResponseBody가 붙은 코드들을 하나씩 나열해 비교해보면
먼저 @PathVariable은 URI에 담긴 값을 가져와 사용하는 것이다.
@RequestParam은 query로 날라오는 key&value 형태에서 key값을 조회에 value값을 가져와 사용하는 것이다.
이떄 GET방식은 URI에 query가 나타나지만 POST방식은 나타나지 않는다.
@ModelAttribute 방식은 객체를 매개변수로 받아 객체의 값에 배정해주시는 식으로 한다.
@RequestBody는 객체를 통해 값을 받는다.
@ModelAttribute와 @RequestBody는 객체에 값을 넣어준다는 공통점이 있다. 하지만 ModelAttribute는 파라미터 값을 DTO에 넣어준다는 특징이 있고 RequestBody는 json과 같은 값을 받는다는 차이점이 있다!
package com.sparta.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {
// [Response header]
// Location: http://localhost:8080/hello.html
@GetMapping("/html/redirect")
public String htmlFile() {
return "redirect:/hello.html";
}
// [Response header]
// Content-Type: text/html
// [Response body]
// * resources/templates/hello.html 의 text 내용
// <!DOCTYPE html>
// <html>
// <head><meta charset="UTF-8"><title>By Templates engine</title></head>
// <body>Hello, Spring 정적 웹 페이지!!</body>
// </html>
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
// [Response header]
// Content-Type: text/html
// [Response body]
// <!DOCTYPE html>
// <html>
// <head><meta charset="UTF-8"><title>By @ResponseBody</title></head>
// <body>Hello, Spring 정적 웹 페이지!!</body>
// </html>
@GetMapping("/body/html")
@ResponseBody
public String helloStringHTML() {
return "<!DOCTYPE html>" +
"<html>" +
"<head><meta charset=\"UTF-8\"><title>By @ResponseBody</title></head>" +
"<body> Hello, 정적 웹 페이지!!</body>" +
"</html>";
}
// [Response header]
// Content-Type: text/html
// [Response body]
// * resources/templates/hello-visit.html 의 text 내용
@GetMapping("/html/dynamic")
public String helloHtmlFile(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
// resources/templates/hello-visit.html
return "hello-visit";
}
private static long visitCount = 0;
// [Response header]
// Content-Type: text/html
// [Response body]
// {"name":"BTS","age":28}
@GetMapping("/json/string")
@ResponseBody
public String helloStringJson() {
return "{\"name\":\"BTS\",\"age\":28}";
}
// [Response header]
// Content-Type: application/json
// [Response body]
// {"name":"BTS","age":28}
@GetMapping("/json/class")
@ResponseBody
public Star helloJson() {
return new Star("BTS", 28);
}
}
model에 addAttribute를 통해 값을 넣으면 자동으로 타임리프가 넣은 값을 조회에 html에 적용한다.
Json형식으로 Response가 하고 싶다면 객체를 넣어서 보내야 한다.!
@Responsebody + @Controller -> @RestController!
이것들을 정리한 표 스파르타코딩클럽 Spring심화반에서 튜터님이 만들어주신 것이다.
출처:https://spartacodingclub.kr/online/spring_plus
스파르타코딩클럽 [Spring 심화반]
Spring 뽀개고 취업하기
spartacodingclub.kr:443
'web study > Spring' 카테고리의 다른 글
Severlet 간단한 사용방법 (0) | 2022.01.26 |
---|---|
Spring으로 간단한 게시판 만들기 (0) | 2022.01.25 |
Spring Dto와 서버와 클라이언트가 통신할 때의 값의 Type (0) | 2022.01.22 |
Spring JPA를 이용한 간단한 CRUD를 하면서 실수한 부분들 (0) | 2022.01.21 |
Spring 컨테이너에 빈 등록하는 2가지 방식 (0) | 2022.01.19 |