요청파라미터를 정말 편리하게 받아보자…
package hello.springmvc.basic.request;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;
@Slf4j
@Controller
public class RequestParamController {
@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");
}
}
전에 만들었던 이 친구를 개선해보자..
@RequestMapping("/request-param-v2")
@ResponseBody //RestApi로 변
public String requestParamV2(
@RequestParam("username") String memberName,
@RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName,memberAge);
//컨트롤러의 반환값이 String이면 반환값과 이름이 같은 뷰를 찾는다.
//그걸 방지하려면 RestApi로 바꿔야 한다.
return "ok";
}
이렇게 전달했을때
로그에 잘 찍히고 있다.
이번에는 여기서 더 개선해보자.
@RequestMapping("/request-param-v3")
@ResponseBody
public String requestParamV3(
@RequestParam String username, //url의 파라미터와 변수명이 이름이 같다면
@RequestParam int age) { //파라미터 바인딩을 생략할 수 있다.
log.info("username={}, age={}", username, age);
//컨트롤러의 반환값이 String이면 반환값과 이름이 같은 뷰를 찾는다.
//그걸 방지하려면 RestApi로 바꿔야 한다.
return "ok";
}
잘 나온다.. 근데 이게 끝이 아니라고 한다…!!
@RequestMapping("/request-param-v4")
@ResponseBody
public String requestParamV4(String username, int age) { //사실 걍 다 생략가능하다..
log.info("username={}, age={}", username, age);
//컨트롤러의 반환값이 String이면 반환값과 이름이 같은 뷰를 찾는다.
//그걸 방지하려면 RestApi로 바꿔야 한다.
return "ok";
}
사실 요청 파라미터와 변수명이 같다면 애너테이션까지 생략가능하다…