Back End/☠️ Java
Model & ModelAndView & redirect
James Wetzel
2024. 9. 20. 19:33
Model
@GetMapping("/example")
public String showExample(Model model) {
model.addAttribute("message", "Hello, World!");
return "exampleView";
}
ModelAndView
@Controller
public class MyController {
@GetMapping("/greeting")
public ModelAndView greeting() {
ModelAndView modelAndView = new ModelAndView("greeting"); // 뷰 이름 설정 (greeting.jsp)
modelAndView.addObject("message", "안녕하세요!"); // 뷰로 전달할 데이터
return modelAndView;
}
}
redirect
@Controller
public class MyController {
@PostMapping("/submit")
public String submitForm() {
// 데이터 처리 후 다른 페이지로 리다이렉트
return "redirect:/thankyou";
}
}
redirect 시점에 데이터를 함께 전송 하는 코드
@Controller
public class MyController {
@PostMapping("/submitForm")
public String submitForm(
@RequestParam("name") String name,
RedirectAttributes redirectAttributes
) {
// 데이터를 리다이렉트 후에도 전달할 수 있도록 설정
redirectAttributes.addFlashAttribute("message", "폼 제출 완료!");
redirectAttributes.addAttribute("userName", name); // URL에 파라미터 추가
return "redirect:/success";
}
@GetMapping("/success")
public String successPage(
@ModelAttribute("message") String message,
@RequestParam("userName") String userName
) {
System.out.println("메시지: " + message); // "폼 제출 완료!" 출력
System.out.println("유저 이름: " + userName); // 폼에서 전송된 이름 출력
return "success"; // success.jsp 페이지로 이동
}
}
728x90
반응형