본문 바로가기

Programming/Web-Spring

[SpringBoot] @ModelAttribute 값받을때 null값 나오는 현상

model 

public class Star {
String name;
int age;

public Star(String name, int age) {
this.name = name;
this.age = age;
}
}

괄호(String name, int age)가 있는 생성자로 만들고 

 

Controller

// [Request sample]
// POST http://localhost:8080/hello/request/form/model
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=Robbie&age=95
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}

 

html 

<h2>POST /hello/request/form/model</h2>
<form method="POST" action="/hello/request/form/model">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
<br>

 

html에서 form에 담아 호출하면 null값이 아니라 입력한 값이 나오게 된다.

728x90