Form Post
2023. 12. 12. 20:22ㆍSpring Boot
들어온 Form data를 읽어 들이는 데에는 여러 방법이 있는데
package com.example.demo.form_test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.test;
import jakarta.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/form")
public class form_controller {
@RequestMapping(method = RequestMethod.GET)
public String form_get(Model model) {
model.addAttribute("test", new test());
return "form/form_post";
}
@RequestMapping(method = RequestMethod.POST)
public String form_post(HttpServletRequest req, Model model) {
test test = new test(req.getParameter("title"), req.getParameter("data"));
model.addAttribute("test", test);
return "form/form_get";
}
}
우선 HttpServletRequest 객체로 읽어 들일 수 있다
이떄 getParameter이라는 method로 key값을 활용하여 각각의 값을 읽어 들인다
@RequestMapping(method = RequestMethod.POST)
public String form_post(@ModelAttribute test test, Model model) {
model.addAttribute("test", test);
return "form/form_get";
}
@ModelAttribute를 이용하여 객체로 값을 읽어 들일 수 있으며
@RequestMapping(method = RequestMethod.POST)
public String form_post(@RequestParam String title, @RequestParam String data, Model model) {
model.addAttribute("test", new test(title, data));
return "form/form_get";
}
@RequestParam을 이용하여 각각의 key값에 따른 값을 읽어 들일 수도 있다
이때 각 변수의 이름을 key값으로 하면 된다
'Spring Boot' 카테고리의 다른 글
| Json Web Token (2) | 2024.01.02 |
|---|---|
| CustomFilter (0) | 2024.01.02 |
| SecurityFilterChain (0) | 2024.01.02 |
| MongoDB (0) | 2023.12.28 |
| CSRF Token (0) | 2023.12.28 |