通过读取数据库中的值,使用ThymeLeaf显示下拉项。

时间:2018-06-15 15:32:28

标签: spring hibernate spring-mvc spring-boot thymeleaf

我正在开发一个Spring Boot应用程序,并尝试使用数据库的内容填充HTML中的选项。为此,我在ThymeLeaf中使用迭代器来显示所有这些选项。该片段是:

<div class="col-1.5">
                        <select class="form-control form-control-sm" id="agentName">

                            <option value="">Select an agent</option>
                            <option th:each="log:${logs}"
                                    th:value="${log.agentName}"
                                    th:text="${log.agentName}"
                            >
                            </option>
                        </select>
                    </div>

我在DAO课程中有这个

@Transactional
@Repository
public interface AgentsDao extends CrudRepository<Agents,String>{       
    public List<Agents> findAll();
    public Agents findByagentId();    
}

我在控制器中有这个

@RequestMapping(value="/log")
    public String log(Model model) {
        List<Agents> logs = agentsCRUD.findAll();
        model.addAttribute("logs", logs);
        return "log";
    }

基本上我在代理模型(表)中使用“agentId”作为主键。并且有数千个代理,它们的名称由列表示:“agentName”所有“agentName”是我试图在使用ThymeLeaf的HTML选项中显示的内容。现在代码有bug。我是Spring Framework的新手(只用了一个星期),所以我很难搞清楚如何做到这一点。

3 个答案:

答案 0 :(得分:0)

确定你有'agentName&#39;在您的代理商&#39;类。 此外,您是否尝试从数据库中获取代理列表时获取整个实体。 我的意思是,如果您只想获取&#39; agentName&#39;,请使用&#39; ResultTransformer&#39;在您的查询中获取'agentName&#39; (如果你正在使用Hibernate Framework的话)。

答案 1 :(得分:0)

对于下拉列表的返回列表,最安全的方法是使用

  

的ModelAttribute

   @ModelAttribute("logs")
    public List<Agents> log() {
        List<Agents> logs = agentsCRUD.findAll();
        return logs;
    }

试试这个。

答案 2 :(得分:0)

public Agents findByagentId();方法中,您需要为代理ID添加参数。例如:public Agents findByagentId(Long id); Spring正在期待一个参数,因此在启动和/或创建Bean时失败了。