SpringBoot——html调用thymeleaf实现数据的读取

1、新建service层

@Service("name")
public class NameService {
    @Autowired
    private UserService userservice;

    public List<User> list(){
        return userservice.selectUserList();
    }
}

注意加@Service("name")和 @Autowired两个注解,其中@Service中的name便是thymeleaf中调用的名 UserService就不贴代码,selectUserList()就是一个遍历用所有用户的方法

2、thymeleaf的调用

<select name="userList" th:with="type=${@name.list()}">
                        <option value="">所有用户</option>
                        <option th:each="dict : ${type}" th:text="${dict.user_name}" th:value="${dict.user_id}"></option>
 </select>

其中type代表list()方法的结果,是一个List,然后通过th:each遍历每个结果并使用dict接收。user_name和user_id是User这一实体类下的字段名

3、最终结果

数据表:user 前段显示

经验分享 程序员 微信小程序 职场和发展