TIL | [Spring] Controller에서 Response
개인 과제를 할 때마다 헷갈리는 부분이었어서 간단하게 정리해보려고 한다. 정리용으로 쓰는 글이라 대부분의 설명이 생략될 것 같으니 참고하면 좋겠다.
참고
정적 웹페이지
1. static 폴더
src -  main - resources - static에 home.html 파일을 만들고 localhost:8080/home.html에 들어가면 Controller를 거치지 않고 스프링에서 resources/static에서 해당 파일을 찾아 화면에 보여준다.
2. Redirect
HomeController
@Controller
public class HomeController {
    @GetMapping("/html/redirect")
    public String staticHtmlFile() {
        return "redirect:/home.html";
    }
}http://localhost:8080 /html/redirect - request
http://localhost:8080 /home.html - response(redirect:/home.html)
3. View 템플릿(Thyemleaf 기준)
src - main - resources - templates - hello.html 파일 생성
HomeController
@Controller
public class HomeController {
    @GetMapping("html/templates")
    public String htmlTemplates() {
        return "hello";
    }
}http://localhost:8080 /html/templates - request
Thyemleaf를 통해 리턴된 String "hello"를 View name으로 인식
→ resources/templates에서 "hello.html"을 찾아 화면에 나타낸다
4. @ResponseBody
HomeController
@GetMapping("/body/html")
@ResponseBody
public String helloStringHTML() {
    return "<!DOCTYPE html>" +
           "<html>" +
               "<head><title>By @ResponseBody</title></head>" +
               "<body> Hello, 정적 웹 페이지!!</body>" +
           "</html>";
}View를 통하지않고 return에 담긴 String 내용을 화면에 나타내준다.
(3.과 내용은 같은나 View를 통하지 않는다는 것에서 큰 차이가 있다.)
http://localhost:8080 /body/html - request
동적 웹페이지
src - main - resources - templates - hello-visit.html 파일 생성
hello-visit.html
방문자수 부분이 페이지가 새로고침 될 때마다 동적으로 변한다.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello Spring</title></head>
<body>
    <div>
        Hello, Spring 동적 웹 페이지입니다!
    </div>
    <div>
        (방문자 수: <span th:text="${visits}"></span>)
    </div>
</body>
</html>HomeController
@Controller
public class HomeController {
    private static long visitCount = 0;
    @GetMapping("/html/dynamic")
    public String helloHtmlFile(Model model) {
        visitCount++;
        model.addAttribute("visits", visitCount);
        return "hello-visit";
    }
}http://localhost:8080 /html/dynamic - request
JSON 데이터
Star.java
@AllArgsConstructor
@Getter
@Setter
public class Star {
    String name;
    int age;
}HomeController
Model 정보 - ${visits}
@Controller
public class HomeController {
    @GetMapping("/json/class")
    @ResponseBody
    public Star helloJson() {
        return new Star("유재석", 51);
    }
}Controller의 반환 타입이 String이 아니라 Star라는 객체라는 점과, Resonse Header의 Content-Tpye이 application/json임을 확인 할 수 있다.
http://localhost:8080 /json/class - request
+ @RestController
@Controller와 @Responsebody를 합쳐 놓은 어노테이션이다. - View를 통하지 않고 데이터 반환
Response 요약
Author And Source
이 문제에 관하여(TIL | [Spring] Controller에서 Response), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hyemco/TIL-Spring-Controller에서-Response와-Request저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)