I want to insert a set of values and display a list of inserted data on the same page. What should I do in the controller class?
Here are all my codes
UserController.java
package com.crud.controll;
import com.crud.model.UserEntity;
import com.crud.service.UserDao;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
private final UserDao userDao;
public UserController(UserDao userDao) {
super();
this.userDao = userDao;
}
@GetMapping("/home")
public String Home(Model model){
List<UserEntity> users = userDao.findBookAll();
model.addAttribute("users", users);
model.addAttribute("userForm", new UserEntity());
return "display";
}
@PostMapping("/home")
public String createUser(@ModelAttribute UserEntity userEntity, Model model) {
userDao.createANewUser(userEntity);
return "display";
}
}
So, this is the page that i want
CodePudding user response:
I think it will be easy if you update your method as follows:
@GetMapping("/home")
public Model Home(Model model){
List<UserEntity> users = userDao.findBookAll();
model.addAttribute("users", users);
model.addAttribute("userForm", new UserEntity());
return model;
}
CodePudding user response:
I recommend Post/Redirect/Get pattern.
If you do not need info about inserted user use this:
@PostMapping("/home")
public String createUser(@ModelAttribute UserEntity userEntity, Model model) {
userDao.createANewUser(userEntity);
return "redirect:/home";
}
If you need info about inserted user, you can use flash attributes:
@PostMapping("/home")
public RedirectView createUser(@ModelAttribute UserEntity userEntity, Model model, RedirectAttributes redirectAttributes) {
userDao.createANewUser(userEntity);
redirectAttributes.addFlashAttribute ("newUser", userEntity);
return new RedirectView("/home", true);
}
and in Home method use:
@GetMapping("/home")
public String Home(Model model, HttpServletRequest request){
List<UserEntity> users = userDao.findBookAll();
model.addAttribute("users", users);
model.addAttribute("userForm", new UserEntity());
Map<String, ?> inputFlashMap =
RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
UserEntity newUser = (UserEntity) inputFlashMap.get("newUser");
model.addAttribute("newUser", newUser);
}
return "display";
}
Or you can put newUser into userForm property to fill out form.
More info about flash attributes: Link. Maybe there is even nicer way to extract flash attributes in Home method.
