클라이언트에서 서버로 데이터를 요청하는 방식
1. 쿼리파라미터 (Get방식)
URL에 ? &등을 이용해서 데이터를 담아 전달한다. URL이 노출되므로 보안에 취약하며, 길이 제한이 있다.
검색, 필터, 페이징등에서 이 방식을 사용한다.
2. Html Form (Post방식)
Message Body를 통해서 데이터가 전달 된다. 회원가입, 상품주문등에서 주로 사용된다,
<form action="/user/signin" method="post">
<div class="form-group">
<label for="username">아이디</label>
<input type="username" name="username" id="username" placeholder="아이디를 입력하세요" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for="password">패스워드</label>
<input type="password" class="form-control form-control-lg" placeholder="패스워드를 입력하세요" name="password" id="password">
</div>
<input type="submit" value="로그인" href="/" class="btn btn-dark btn-block col-sm-1 " style="display:inline-block" >
<a href="https://kauth.kakao.com/oauth/authorize?client_id=19ec158ac89f2be7a8713d1bec482fb9&redirect_uri=http://13.209.86.236:8080//auth/kakao/callback&response_type=code"><img height="38px" src="/images/kakao_login_button.png" /></a>
<br /> <br />
<span > 아직 계정이 없으신가요? <a class="linkControl" href="/user/signup">회원가입</a></span>
<br>
</form>
3. Http message body에 직접 데이터를 담아서 요청한다.
데이터 형식은 주로 json 형태이며, Post/Put/Patch방식에서 주로 사용된다.
(@RequesyBody, @ResponseBody, @RestController 등 이용)
서버에서 요청을 조회하는 방법
1. request.getparameter()를 이용하면 쿼리파라미터와 html 폼 두 가지 요청 파라미터를 조회할 수 있다..
(두 가지 형식이 같기 때문에) 이를 요청 파라미터 조회라고한다.
@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");
}
2. @RequestParam
@ResponseBody
@RequestMapping("/request-param-v2")
public String requestParamV2(
@RequestParam("username") String memberName,
@RequestParam("age") int memberAge){
log.info("username={}, age={}",memberName,memberAge);
return "ok";
}
간단하게 어노테이션을 이용하여 요청 파라미터를 조회할 수 있다.
@ResponseBody는 컨트롤러 클래스내부의 메소드에 붙이면, @RestController와 동일한 역할을 한다. (뷰 조회를 하지않고 문자가 http응답으로 리턴된다)
public String requestParamV3(
@RequestParam String username,
@RequestParam int age){
log.info("username={}, age={}",username,age);
return "ok";
다음처럼 문자열을 생략할 수도 있다. 어노테이션 자체를 생략하는 방식도 가능하지만, 코드가 명확해보이려면 어노테이션까지는 생략하지 않는것이 좋다.
required라는 속성이 존재하는데, 디폴트 값은 true이다. 이를 false로 바꿔서 명시하지 않을경우 파라미터값을 할당하지않으면 에러가난다.
※ int값은 기본형 변수라서 null이 들어갈 수 없으므로, 위 코드에서 int보다 Integer형을 사용하는것이 좋다
또는 defaultValue라는 속성을 이용한다.
@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap){
log.info("username={}, age = {}", paramMap.get("username"),paramMap.get("age"));
return "ok";
}
}
또한 위 코드처럼 Map을 이용해서도 파라미터를 조회할 수 있다.
3. @ModelAttribute
@ResponseBody
@RequestMapping("/model-attributev1")
public String mvV1(@ModelAttribute HelloData helloData){
log.info("username={}, age = {}", helloData.getUsername(),helloData.getAge());
return "ok";
}
@ModelAttribue 어노테이션을 이용하면 객체와 세터를 이용하여 입력 파라미터 값이 셋팅되고, 게터를 이용하여 파라미터를 조회한다.
@ModelAttribute는 생략가능하다. @RequestParam도 생략가능하다. => 혼란이 있을 수 있다.
생략시 스프링은 다음과 같은 규칙을 사용한다.
int, String, Integer같은 기본 타입은 @RequestParam, / 나머지는 @ModelAttribute 이용
'스프링 > 핵심원리+MVC' 카테고리의 다른 글
스프링 - HTTP 요청 메세지 (단순텍스트와 json) (0) | 2021.08.10 |
---|---|
스프링 - 빈 스코프 (0) | 2021.07.27 |
스프링 - 싱글톤 컨테이너 / 컴포넌트 스캔 (0) | 2021.07.27 |
스프링 - 객체지향 (0) | 2021.07.26 |
스프링 - 빈 생명주기. @PreDestory, @PostConstruct (0) | 2021.07.24 |