Spring boot 입출력

su dong·2023년 7월 3일
0

받아오는 것 - json일 때


private ObjectMapper objectMapper = new ObjectMapper();


@ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(@RequestBody String messageBody) throws IOException {
        log.info("messageBody={}", messageBody);
        HelloData data = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        return "ok";
}

@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(@RequestBody HelloData helloData) throws IOException {
        log.info("messageBody={}", helloData);
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        return "ok";
}

출력하는 것 - thymeleaf

package hello.springmvc.basic.response;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ResponseViewController {
    @RequestMapping("/response-view-v1")
    public ModelAndView responseViewV1() {
        ModelAndView mav = new ModelAndView("/response/hello");
        mav.addObject("data", "hello!");

        return mav;
    }

    @RequestMapping("/response-view-v2")
    public String responseViewV2(Model model) {
        model.addAttribute("data","hello22");

        return "/response/hello";
    }
}

출력하는것 2 - http api, 메세지 바디에 직접 입력

package hello.springmvc.basic.response;


import hello.springmvc.basic.HelloData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class ResponseBodyController {

   

    @ResponseBody
    @GetMapping("/response-body-string-v3")
    public String responseBodyV3(HttpServletResponse response) throws IOException {
        return "ok";
    }

  
	@ResponseStatus(HttpStatus.ACCEPTED)
    @ResponseBody
    @GetMapping("/response-body-string-v5")
    public HelloData responseBodyV5(){
        HelloData helloData = new HelloData();
        helloData.setUsername("jisu");
        helloData.setAge(11);

        return helloData;
    }
}
profile
사람들을 돕는 문제 해결사, 개발자 sudong입니다. 반갑습니다. tkddlsqkr21@gmail.com

0개의 댓글