无法在 Thymeleaf 中显示 Spring Boot 模型数据

Posted

技术标签:

【中文标题】无法在 Thymeleaf 中显示 Spring Boot 模型数据【英文标题】:Unable to Display Spring Boot Model Data in Thymeleaf 【发布时间】:2020-10-02 08:40:34 【问题描述】:

您好,我目前正在开发一个 Spring Boot Web 应用程序,它为经过身份验证的用户提供项目管理仪表板。该应用程序目前由 3 个主要实体类组成:用户、角色和项目。 Role 和 Project 都与类 User 具有 ManyToMany 关系。我正在使用 Thymeleaf 在我的 html 模板中显示对象数据,但它似乎没有正确地从我的控制器中提取我的数据。

每当我调用所有用户详细信息并将当前用户与数据行匹配有效

<div th:each="allUser:$allUsers">
               <div th:if="$#authentication.getName() == allUser.username">
                <span class="d-none d-lg-inline text-gray-600 small" th:text="$allUser.firstName"></span>
                <span class="mr-4 d-none d-lg-inline text-gray-600 small" th:text="$allUser.lastName"></span>
                </div>
               </div>

但是,当让当前用户进入我的控制器时它不起作用

<div th:each="user:$users">
               <div th:if="$#authentication.getName() == user.username">
                <span class="d-none d-lg-inline text-gray-600 small" th:text="$user.firstName"></span>
                <span class="mr-4 d-none d-lg-inline text-gray-600 small" th:text="$user.lastName"></span>
                </div>
               </div>

此外,我正在尝试显示分配给当前用户的项目的项目信息,但也不会将任何内容打印到仪表板:

<tr th:each="project:$projects">
                      <td th:text="$project.pxprojectname"></td>
                      <td th:text="$project.initialpendingid"></td>
                      <td th:text="$project.currentpendingid"></td>
                      <td th:text="$project.completionstatus"></td>
                      <td th:text="$project.manager"></td>
                      </tr>

我的代码可以在下面找到:

用户类

@Entity
@Table(name = "pxuser")
public class User 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "tabid")
    private int tabid;

    @Column(name = "username")
    private String username;

    @Column(name = "firstname")
    private String firstName;

    @Column(name = "lastname")
    private String lastName;

    @Column(name = "password")
    private String password;

    @Column(name = "active")
    private boolean active;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "pxuser_role", joinColumns = @JoinColumn(name = "tabid"), inverseJoinColumns = @JoinColumn(name = "auth_role_id"))
    private Set<Role> roles = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "pxassignment", joinColumns = @JoinColumn(name = "usertabid"), inverseJoinColumns = @JoinColumn(name = "pxprojectid"))
    private Set<Project> projects = new HashSet<>();

    public User() 

    

    public User(User user) 
        this.tabid = user.getTabid();
        this.username = user.getUsername();
        this.firstName = user.getFirstName();
        this.lastName = user.getLastName();
        this.password = user.getPassword();
        this.active = user.isActive();
        this.roles = user.getRoles();
        this.projects = user.getProjects();
    

    public int getTabid() 
        return tabid;
    

    public void setTabid(int tabid) 
        this.tabid = tabid;
    

    public String getUsername() 
        return username;
    

    public void setUsername(String username) 
        this.username = username;
    

    public String getFirstName() 
        return firstName;
    

    public void setFirstName(String firstName) 
        this.firstName = firstName;
    

    public String getLastName() 
        return lastName;
    

    public void setLastName(String lastName) 
        this.lastName = lastName;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public boolean isActive() 
        return active;
    

    public void setActive(boolean active) 
        this.active = active;
    

    public Set<Role> getRoles() 
        return roles;
    

    public void setRoles(Set<Role> roles) 
        this.roles = roles;
    

    public Set<Project> getProjects() 
        return projects;
    

    public void setProjects(Set<Project> projects) 
        this.projects = projects;
    


项目类

@Entity
@Table(name = "pxproject")
public class Project 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "pxprojectid")
    private String pxprojectid;

    @Column(name = "pxprojectname")
    private String pxprojectname;

    @Column(name = "servername")
    private String servername;

    @Column(name = "initialpendingid")
    private int initialpendingid;

    @Column(name = "currentpendingid")
    private int currentpendingid;

    @Column(name = "completionstatus")
    private String completionstatus;

    @Column(name = "isactive")
    private boolean isactive;

    @Column(name = "sfengagementid")
    private String sfengagementid;

    @Column(name = "manager")
    private String manager;

    @ManyToMany(mappedBy = "projects")
    private Set<User> user = new HashSet<>();


    public Project() 
    

    public Project(String pxprojectid, String pxprojectname, String servername, int initialpendingid, int currentpendingid, String completionstatus, boolean isactive, String sfengagementid, String manager, Set<User> users) 

        this.pxprojectid = pxprojectid;
        this.pxprojectname = pxprojectname;
        this.servername = servername;
        this.initialpendingid = initialpendingid;
        this.currentpendingid = currentpendingid;
        this.completionstatus = completionstatus;
        this.isactive = isactive;
        this.sfengagementid = sfengagementid;
        this.manager = manager;
        this.user = user;

    

    public String getPxprojectid() 
        return pxprojectid;
    

    public void setPxprojectid(String pxprojectid) 
        this.pxprojectid = pxprojectid;
    

    public String getPxprojectname() 
        return pxprojectname;
    

    public void setPxprojectname(String pxprojectname) 
        this.pxprojectname = pxprojectname;
    

    public String getServername() 
        return servername;
    

    public void setServername(String servername) 
        this.servername = servername;
    

    public int getInitialpendingid() 
        return initialpendingid;
    

    public void setInitialpendingid(int initialpendingid) 
        this.initialpendingid = initialpendingid;
    

    public int getCurrentpendingid() 
        return currentpendingid;
    

    public void setCurrentpendingid(int currentpendingid) 
        this.currentpendingid = currentpendingid;
    

    public String getCompletionstatus() 
        return completionstatus;
    

    public void setCompletionstatus(String completionstatus) 
        this.completionstatus = completionstatus;
    

    public boolean isIsactive() 
        return isactive;
    

    public void setIsactive(boolean isactive) 
        this.isactive = isactive;
    

    public String getSfEngagementid() 
        return sfengagementid;
    

    public void setSfEngagementid(String sfengagementid) 
        this.sfengagementid = sfengagementid;
    

    public String getManager() 
        return manager;
    

    public void setManager(String manager) 
        this.manager = manager;
    

    public Set<User> getUser() 
        return user;
    

    public void setUser(Set<User> user) 
        this.user = user;
    


角色类

@Entity
@Table(name = "pxrole")
public class Role 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "auth_role_id")
    private int auth_role_id;

    @Column(name = "role_name")
    private String role_name;

    @Column(name = "role_desc")
    private String role_desc;

    public Role() 

    

    public int getAuth_role_id() 
        return auth_role_id;
    

    public void setAuth_role_id(int auth_role_id) 
        this.auth_role_id = auth_role_id;
    

    public String getRole_name() 
        return role_name;
    

    public void setRole_name(String role_name) 
        this.role_name = role_name;
    

    public String getRole_desc() 
        return role_desc;
    

    public void setRole_desc(String role_desc) 
        this.role_desc = role_desc;
    

控制器

@Controller
public class HomeController 

     @Autowired 
     ProjectRepository projectRepository;

     @Autowired 
     ProjectService projectService;

     @Autowired 
     UserRepository userRepository;

     @Autowired 
     CustomUserDetailsService customUserDetailsService;


    @GetMapping("/")
        public String index() 
            return "index";
        


    @GetMapping("/dashboard")
    public String dashboard(Model model, String currentUser)   


        List<Project> projectList = projectRepository.findByUser_Username(currentUser);

        List<User> userList = customUserDetailsService.getAllUsersDetails();

        User user = userRepository.findByUsername(currentUser);

        model.addAttribute("projects", projectList);
        model.addAttribute("allUsers", userList);
        model.addAttribute("users", user);

        return "index";
    

    @GetMapping("/admin")
    public String admin() 
        return "admin";
    

     // Login form
    @GetMapping("/login")
        public String login() 
        return "login";
    

    @GetMapping("/logout")
    public String logout() 
    return "login?logout";


    @GetMapping("/dashboard/projects")
    public String projects() 
        return "projects";
    

    @GetMapping("/error")
    public String error() 
        return "error";
    

用户存储库

public interface UserRepository extends JpaRepository<User, Integer>
    public User findByUsername(String username);

项目存储库

public interface ProjectRepository  extends JpaRepository<Project, Integer>
    List<Project> findByUser_Username(String username);

自定义用户详细信息服务

@Service
public class CustomUserDetailsService implements UserDetailsService

    @Autowired
    UserRepository userRepository;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException

        User user = userRepository.findByUsername(username);


        if (user == null) 
            throw new UsernameNotFoundException("Invalid username or password.");
               
        return new CustomUserDetails (user);
       
    public List<User> getAllUsersDetails()     
        return userRepository.findAll();
    

项目服务

@Service
public class ProjectService 

    @Autowired
    private ProjectRepository projectRepository;

    //Return List of All Projects
    public List<Project> getProjects()
        return projectRepository.findAll();

        

    //Return List of Projects by Username
    public List<Project> getProjectsByUserUsername(String username)
        return projectRepository.findByUser_Username(username);
       

非常感谢任何帮助! 谢谢!!!

【问题讨论】:

【参考方案1】:

在控制器中为 GetMapping("/dashboard") currentUser 变量保存值 null,

因此User user = userRepository.findByUsername(currentUser); -> 输出可选对象。

List&lt;Project&gt; projectList = projectRepository.findByUser_Username(currentUser); -> 输出空列表。 因此无法显示数据。

通过使用 Authentication 或 Principle 对象,我们可以取出当前登录的用户。

【讨论】:

【参考方案2】:

你已经遍历了users like list &lt;div th:each="user:$users"&gt;,但是从控制器中,你将它作为单个对象传递。

User user = userRepository.findByUsername(currentUser);

        model.addAttribute("users", user);

要么从html 中删除循环,要么从控制器传递一个列表。

【讨论】:

我已尝试删除 ,但这似乎不起作用。正如这里提到的 (***.com/a/35092065/13237132),使用 "$#authentication.getPrincipal().getUser().getFirstName()" 确实有效,但是,我仍然无法调用我用户的项目对象。有任何想法吗?再次感谢!!!

以上是关于无法在 Thymeleaf 中显示 Spring Boot 模型数据的主要内容,如果未能解决你的问题,请参考以下文章

Thymeleaf 无法显示用户的用户名和角色

无法使用 Spring Boot thymeleaf 加载图像

有没有办法在 thymeleaf 和 spring boot 中显示来自 MySql 数据库的图像?

Thymeleaf和Spring安全无法正常工作[重复]

Thymeleaf-Spring4 无法自动装配 TemplateEngine

Spring Boot + Thymeleaf 找不到消息属性