본문 바로가기

Java/Spring

@RequestParam

RequestParam 어노테이션을 알아보기 앞서 먼저 간단한 코드 예시를 보자.

먼저 백엔드 부분의 코드이다.

 @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
    	model.addAttribute("name", name);
    	return "hello-template";
    }

그리고 프론트엔드 부분의 html이다.

<!DOCTYPE HTML>
<html xmlns:th ="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>hello</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${name} + '님 반갑습니다.'">안녕하세요. 손님</p>
</body>
</html>

그런데 해당 url인 "localhost:8100/hello-mvc" 로 바로 접근할 경우 에러가 발생한다. 에러 내용은 다음과 같다.

Required request parameter 'name' for method parameter type String is not present

문제는 @RequestParam의 옵션 중 required가 있다. 이는 디폴트 값으로 true가 반환되는데, 이럴 경우 url 뒤에 무조건 name의 변수를 할당해주어야 한다. 

 

http://localhost:8100/hello-mvc?name=moon 이런식으로 물음표 뒤에 name= "원하는 데이터 값" 을 넣어주면 된다.

http://localhost:8100/hello-mvc?name=moon

잘 나온다.

 

addAttribute("name", name)은 html에서 ${}에 담긴 첫번째 매개변수인 name을 찾아서 두번째 매개변수로 주어진 name, 즉 hello-mvc?name=moon 에서 moon이라는 문자열을 반환해준다.

 

'Java > Spring' 카테고리의 다른 글

Spring + MySQL 연동  (0) 2022.11.24
@RequestParam과 @PathVariable  (0) 2022.11.22
Junit 테스트  (0) 2022.11.03
@ResponseBody  (0) 2022.11.03
GetMapping  (0) 2022.11.03