스프링 MVC 기본 기능

이동건 (불꽃냥펀치)·2025년 1월 10일
0

요청 매핑

 @RestController
 public class MappingController {
     private Logger log = LoggerFactory.getLogger(getClass());

     @RequestMapping("/hello-basic")
     public String helloBasic() {
         log.info("helloBasic");
         return "ok";
     }
}
  • Http 메서드 모두 허용 Get,Head,Post,Put,Patch,Delte
  • @RestController
    • @Controller는 반환 값이 String이면 뷰 이름으로 인식된다. 그 결과 뷰를 찾고 뷰가 렌더링 된다.
    • @RestController는 반환 값으로 뷰를 찾는 것이 아니라 Http메시지 바디에 바로 입력한다.
  • @RequestMapping("/hello-basic)
    • hello-basic URL 호출이 오면 이 메서드가 실행되도록 매핑한다.
    • 대부분의 속성을 배열[]로 제공하므로 다중 설정이 가능하다. {"hello-basic","/hello-go"}
 @RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
 @GetMapping(value="/mapping-get-v1")

위의 코드는 모두 동일한 것이다.

PathVariable(경로변수 사용)

@GetMapping("/mapping/{userId}")
 public String mappingPath(@PathVariable("userId") String data) {
     log.info("mappingPath userId={}", data);
     return "ok";
 }
  • 이 경로는 리소스 경로에 식별자를 넣는 스타일이다.

  • @PathVariable은 매칭 되는 부분을 편리하게 조회할 수 있게하고, 이름과 파라미터 이름이 같으면 생략이 가능하다.

  • @PathVariable 다중 사용

 @GetMapping("/mapping/users/{userId}/orders/{orderId}")
 public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
     log.info("mappingPath userId={}, orderId={}", userId, orderId);
	return "ok";
}



HTTP 요청 - 기본,헤더 조회

@RestController
 public class RequestHeaderController {
     @RequestMapping("/headers")
     public String headers(HttpServletRequest request,
                           HttpServletResponse response,
                           HttpMethod httpMethod,
                           Locale locale,
							@RequestHeader MultiValueMap<String, String> headerMap,
							@RequestHeader("host") String host,
							@CookieValue(value = "myCookie", required = false)){
        log.info("request={}", request);
        log.info("response={}", response);
        log.info("httpMethod={}", httpMethod);
        log.info("locale={}", locale);
        log.info("headerMap={}", headerMap);
        log.info("header host={}", host);
        log.info("myCookie={}", cookie);
        return "ok";
    }
}
  • HttpServletRequest
  • HttpServletResponse
  • HttpMethod:HTTP 메서드를 조회한다
  • Locale: Locale 정보를 조회한다
  • @RequestHeader("host") String host
    • 특정 HTTP 헤더를 조회한다
  • @CookieValue(value="myCookie",required=false)String cookie
    • 특정 쿠키를 조회한다
  • MutivalueMap
    • Map과 유사한데 하나의 키에 여러 값을 받을 수 있다.


요청 파라미터 - 쿼리 파라마터,HTML Form

Get 쿼리 파라미터 전송 예시

http://localhost:8080/request-param?username=hello&age=20

Post,HTML Form 전송

POST /request-param ...
 content-type: application/x-www-form-urlencoded
 username=hello&age=20
  • Get,Post 방식이든 둘다 형식이 같으므로 구분없이 조회할 수 있다.
  • 이것을 쿼리 요청 파라미터 조회라한다.
 @RequestMapping("/request-param-v1")
 public void requestParamV1(HttpServletRequest request, HttpServletResponse response) 
 throws IOException {
         String username = request.getParameter("username");
         int age = Integer.parseInt(request.getParameter("age"));
         log.info("username={}, age={}", username, age);
         response.getWriter().write("ok");
     }

request.getParameter()
여기서는 단순히 HttpServletRequest가 제공하는 방식으로 요청 파라미터를 조회했다.

 @ResponseBody
 @RequestMapping("/request-param-v2")
 public String requestParamV2(
         @RequestParam("username") String memberName,
         @RequestParam("age") int memberAge) {
     log.info("username={}, age={}", memberName, memberAge);
     return "ok";
 }
  • @RequestParam: 파라미터 이름으로 바인딩
  • @ResponseBody: View 조회를 무시하고 Http message body에 직접 해당 내용 입력
  • @RequestParam String username: Http 파라미터 이름이 변수와 같으면 name값을 생략 할 수 있다
  • String username: String,int,Integer등의 단순 타입이면 @RequestParam도 생략이 가능하다

 @RequestParam(required = true) String username
 @RequestParam(required = false) Integer age
  • @RequestParam.required
    • 파라미터 필수 여부
    • 기본값이 파라미터 필수이다
    • /request-param-required?username= 값이 null이 들어와서 오류가 발생한다
    • required=false로 변경시 username값이 null로 들어와도 오류가 발생하지 않는다
    • 기본형에는 null값이 들어갈 수 없다
    • @RequestParam(required = false) int age 경우에는 null이 들어갈 수 없으므로 Integer값으로 변경해야한다

  • defaultValue
    • 파라미터에 값이 없을 경우 defaultValue에 값을 지정하면 기본 값을 적용할 수 있다


  • @RequestParam Map<String,Object> paramMap
    • paramMap.get("age"))로 값을 얻을 수 있다
    • 파라미터의 값이 1개라면 Map을 사용해도 되지만 그렇지 않다면 MultiValueMap을 사용하자



HTTP 요청 파라미터 - @ModelAttribute

 @Data
 public class HelloData {
     private String username;
     private int age;
 }
 @ResponseBody
 @RequestMapping("/model-attribute-v1")
 public String modelAttributeV1(@ModelAttribute HelloData helloData) {
     log.info("username={}, age={}", helloData.getUsername(),
	 helloData.getAge());
     return "ok";
 }
  • 스프링 MVC는 @ModelAttribute가 있으면
    • HelloData 객체를 생성한다
    • 요청 파라미터의 이름으로 HelloData객체의 프로퍼티를 찾는다. 그리고 해당 프로퍼티의 setter를 호출해서 파라미터의 값을 바인딩한다



HTTP 요청 메시지 - 단순 텍스트

  • HTTP message body에 데이터를 직접 담아서 요청
  • 요청 파라미터와 다르게 HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우는 @RequestParam,@ModelAttribute를 사용할 수 없다

@PostMapping("/request-body-string-v1")
public void requestBodyString(HttpServletRequest request,HttpServletResponse response) 
     throws IOException {
         ServletInputStream inputStream = request.getInputStream();
         String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
         log.info("messageBody={}", messageBody);
         response.getWriter().write("ok");
}
  • InputStream(Reader): HTTP 요청 메시지 바디의 내용을 직접 조회
  • OutputStream(Writer): HTTP 응답 메시지의 바디에 직접 결과 출력

 @PostMapping("/request-body-string-v3")
 public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
     String messageBody = httpEntity.getBody();
     log.info("messageBody={}", messageBody);
return new HttpEntity<>("ok");
}
  • HttpEntity: HTTP header,body 정보를 편리하게 조회

    • 메시지 바디 정보를 직접 조회
    • 요청 파라미터를 조회하는 기능과 관계없음
  • HttpEnttiy는 응답에도 사용 가능

    • 메시지 바디 정보 직접 반환
    • 헤더 정보 포함 가능

HttpEntity를 상속받은 다음 객체들도 같은 기능을 제공한다

  • RequestEntity
    • HttpMethod,url 정보가 추가/요청에서 사용
  • ResponseEntity
    • HTTP 상태 코드 설정 가능, 응당에서 사용
    • return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED)



HTTP 요청 메시지 -JSON

@Controller
public class RequestBodyJsonController {
    private ObjectMapper objectMapper = new ObjectMapper();
    @PostMapping("/request-body-json-v1")
    public void requestBodyJsonV1(HttpServletRequest request,HttpServletResponse response) 
    throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream,StandardCharsets.UTF_8);
        log.info("messageBody={}", messageBody);
        HelloData data = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        response.getWriter().write("ok");
    }
}
  • HttpServletRequest를 사용해서 직접 HTTP 메시지 바디에서 데이터를 읽어와서 문자로 변환한다
  • 문자로 된 JSON 데이터를 objectMapper를 사용해서 자바 객체로 변환한다
@RequestBody String messageBody
HelloData data = objectMapper.readValue(messageBody, HelloData.class);
  • @RequestBody를 사용해서 HTTP 메시지에서 데이터를 꺼내고 messageBody에 저장한다
  • 문자로 된 JSON 데이터인 messageBodyobjectMapper를 통해서 자바 객체로 변환한다
 @ResponseBody
 @PostMapping("/request-body-json-v3")
 public String requestBodyJsonV3(@RequestBody HelloData data) {
 		
        log.info("username={}, age={}", data.getUsername(), data.getAge());
   	    return "ok";
 }
  • HttpEntity,@RequestBody를 사용하면 HTTP 메시지 컨버터가 HTTP 메시지 바디의 내용을 우리가 원하는 문자나 객체로 변환해준다.
@ResponseBody
 @PostMapping("/request-body-json-v4")
 public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) {
     HelloData data = httpEntity.getBody();
     log.info("username={}, age={}", data.getUsername(), data.getAge());
     return "ok";
 }
  • 물론 HttpEntity를 활용할 수 있다



HTTP 응답 - HTTP API, 메시지 바디에 직접 입력

 @GetMapping("/response-body-string-v2")
     public ResponseEntity<String> responseBodyV2() {
         return new ResponseEntity<>("ok", HttpStatus.OK);
     }
     
 @GetMapping("/response-body-json-v1")
 public ResponseEntity<HelloData> responseBodyJsonV1() {
         HelloData helloData = new HelloData();
         helloData.setUsername("userA");
         helloData.setAge(20);
         return new ResponseEntity<>(helloData, HttpStatus.OK);
     }
  • HTTP 메시지 컨버터를 사용하지 않고 바로 ResponseEntity로 메시지 바디에 직접 글을 쓸수 있다
  • 물론 @ResponseBody로 Http 메시지 컨버터로 전달하는 방식도 가능하다








출처: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

profile
자바를 사랑합니다

0개의 댓글

관련 채용 정보