Search code examples
javaspringspring-mvcthymeleafspring-annotations

How to make form input and the value table be on the same page with Spring MVC and Thymleaf?


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

Image


Solution

  • 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;
        }