首页 > 解决方案 > java spring boot将数据传递到前端

问题描述

我们有我正在努力的家庭作业。我首先要做的是将数据传递给前端。这是我的项目结构。
在此处输入图像描述

我想将所有用户打印到前端。

用户服务

@Service
    public class UserService {
        private final Map<Long, User> users;

        public UserService(Map<Long, User> users) {
            this.users = users;
        }

        public Map<Long, User> findAllUsers() {
            return users;
        }
    }

用户控制器

@Controller
@RequestMapping("/user")

public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/")
    public String all(Model model) {
        model.addAttribute("users", userService.findAllUsers() );
        return "user/all";
    }
}

运行应用程序的 main 以及我正在创建两个用户的位置

@Slf4j
@Controller
@SpringBootApplication
public class MvcListApplication implements CommandLineRunner {



    public static void main(String[] args) {

        Engine company = new Engine();
        User user;
        User employee;
        user = company.createUser("fsdfsd","fsdfsd",49484894,"gfdgfdg@fdgfd.com",918191,"fsdfsd","Ulica",456);
        employee = company.createUser("fsdfsd","fsdfsd",494894,"gfdgfdg@fdgfd.com",918191,"fyrtytr","Ulica",456);

        SpringApplication.run(MvcListApplication.class, args);
        log.info("Open in browser: http://localhost:8080");
    }

    @Override
    public void run(String... args) throws Exception {

    }


}

用户类

    public class User {

        private String ID;
        private String firstName;
        private String lastName;
        private int idNumber;
        private String email;
        private Address officialAddress;
        private Address postAddress;
        private List<String> contracts = new ArrayList<>();


        public User(String firstName, String lastName, int idNumber, String email, Address officialAddress, Address postAddress) {
            ID = UUID.randomUUID().toString();
            setFirstName(firstName);
            setLastName(lastName);
            setIdNumber(idNumber);
            setEmail(email);
            setOfficialAddress(officialAddress);
            setPostAddress(postAddress);
        }

getters/setters

还有我的前端模板/用户/全部

<tr th:each="user: ${users}">
    <td th:text="${user.id}"></td>
    <td th:text="${user.firstName}"></td>
    <td th:text="${user.lastName}"></td>
</tr>

我只是想把一些东西粘在一起让它工作,但它就是行不通。它运行但我看不到任何结果,没有用户只在 url /users 上硬编码 html。谢谢你的帮助

标签: javaspring-bootspring-mvc

解决方案


users是类型Map。要显示所有用户,请values使用Map.

<tr th:each="user: ${users.values()}">
    <td th:text="${user.id}"></td>
    <td th:text="${user.firstName}"></td>
    <td th:text="${user.lastName}"></td>
</tr>

推荐阅读