Spring Boot 쿼리 파라미터, HTML Form

목차

Spring Boot 쿼리 파라미터, HTML Form

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/request-param-v1" method="post">
username: <input type="text" name="username"/> age: <input type="text" name="age"/>
<button type="submit">전송</button>
</form>
</body>
</html>

HttpServletRequest 객체 내 메소드 사용하기

@Slf4j
@RestController
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");
}
}

RequestParam 어노테이션 사용하기

@RequestMapping("/request-param-v2")
@ResponseBody
public String requestParamV2(
@RequestParam("username") String memberName,
@RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName, memberAge);
return "ok";
}
@RequestMapping("/request-param-v3")
@ResponseBody
public String requestParamV3(
@RequestParam String username,
@RequestParam int age) {
log.info("username={}, age={}", username, age );
return "ok";
}
@RequestMapping("/request-param-v4")
@ResponseBody
public String requestParamV4(String username, int age) {
log.info("username={}, age={}", username, age );
return "ok";
}
@RequestMapping("/request-param-required")
@ResponseBody
public String requestParamV5(
@RequestParam(required = true) String username,
@RequestParam(required = false) Integer age) {
log.info("username={}, age={}", username, age );
return "ok";
}
@RequestMapping("/request-param-default")
@ResponseBody
public String requestParamDefault(
@RequestParam(required = true, defaultValue = "guest") String username,
@RequestParam(required = false, defaultValue = "-1") Integer age) {
log.info("username={}, age={}", username, age );
return "ok";
}
@RequestMapping("/request-param-map")
@ResponseBody
public String requestParamMap(@RequestParam Map<String, Object> paramMap){
log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));
return "ok";
}

DTO 이용하기

@Data
public class HelloData {

private String username;
private int age;
}
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@RequestParam String username, @RequestParam int age){
HelloData helloData = new HelloData();
helloData.setUsername(username);
helloData.setAge(age);

log.info("username = {}, age = {}", helloData.getUsername(), helloData.getAge());
log.info("helloData={}", helloData);

return "ok";
}

ModelAttribute 어노테이션 이용하기

@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(@ModelAttribute HelloData helloData){
log.info("username = {}, age = {}", helloData.getUsername(), helloData.getAge());
log.info("helloData={}", helloData);

return "ok";
}
Share