[스프링 입문] 스프링 웹 개발 기초

chaen-ing·2023년 8월 6일
0

Spring 공부

목록 보기
1/13

스프링 웹 개발 기초

1. 정적 컨텐츠

파일을 그냥 그대로 웹브라우저에 전달해주는 것

웹브라우저 접속 → 내장 톰켓 서버 → 스프링에게 넘김

→ 1. 컨트롤러(우선순위가짐)에서 hello-static 찾음 → 없다

→ 2. resource 파일안의 hello-static 찾음 → 반환

2. MVC와 템플릿 엔진

서버에서 변형해서 html을 바꿔서 웹브라우저에 전달하는 것

MVC : Model, View, Controller

예전에는 나눠져 있지않고 view 파일만 있었음.

현재는
view : 화면 그리는 작업
controller : 비즈니스 로직, 서버 관련


@Controller
public class HelloController {

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

@RequestParam : 외부에서 파라미터를 받음

http 접속시 hello spring!이라는 문구가 뜬다

→ String name의 name = spring!으로 바뀌는 것

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

태그안의 hello! empty는 써도 안써도 상관없음

→ thymeleaf 장점으로, 서버없이 그냥 html 파일 복사해서 열어봐도 껍데기가 나온다. 이때나오는 문구가 hello! empty

→ 템플릿 엔진으로 열때는(서버를 파서 열때) text 안의 내용으로 치환된다

helloController : hello-template 리턴, model(name:spring)

→ 스프링에게 넘겨줌 viewResolver : 뷰와 관련된 것 처리

→ return과 같은애를 찾은 후, 변환을 한 html파일을 넘겨줌

3. API

@GetMapping("hello-string")
@ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello"+name;
    }

@ResponseBody : body부에 해당 내용을 직접 넣어주겠다는 의미

템플릿 엔진과의 차이점은 뷰가 없음

접속 후 페이지 소스를 보면 Html태그도 없음

이번에는 문자가 아닌 데이터를 넘겨 보겠다

@GetMapping("hello-api")
@ResponseBody
    public Hello helloApi(@RequestParam("name")String name){
        Hello hello = new Hello(); // 객체 생성
        hello.setName(name); // 객체 setname
        return hello; // 객체를 넘겨줌
    }

    static class Hello{
        private String name;

        public String getName(){
            return name;
        }

        public void setName(String name){
            this.name = name;
        }
    }

Hello라는 객체를 생성하고 넘겨줌

  • 자바 bean 방식 or getter and setter or property 접근 방식

    : private한 변수에 접근하기위해 public method 사용

페이지 열었을때
{"name" : "spring!"} 문구가 표시됨

→ json이라는 키 : 값 구조 이용하는 방식

→ @ResponseBody 를 사용하고, 객체를 반환하면 자동으로 객체가 JSON으로 변환됨

@ResponseBody 를 사용

  • HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter 가 동작
  • 기본 문자처리: StringHttpMessageConverter
  • 기본 객체처리: MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

인프런 스프링 입문 - 김영한 강의를 듣고 정리한 내용입니다

profile
💻 개발 공부 기록장

1개의 댓글

comment-user-thumbnail
2023년 8월 6일

좋은 글 감사합니다.

답글 달기

관련 채용 정보