如何使用Spring从mysql到jsp检索数据

时间:2018-09-25 10:28:15

标签: java spring jsp

这是我的DAO代码

 public List<UserBean> getdata(UserBean userBean) 
        {
            return this.jdbcTemplate.query("select username from customer", new RowMapper<UserBean>() {

                public UserBean mapRow(ResultSet rs, int rowNum) throws SQLException 
                {
                    UserBean ub = new UserBean();
                    ub.setUsername(rs.getString(1));

                    return ub;
                }

            });
        }

这是我的控制器代码

 if(retrieveService.getdata(userBean) != null)
 { 
List<UserBean> list=retrieveService.getdata(userBean);
 return new ModelAndView("welcomes", "list", list); 
}

这是我的jsp代码

<ul id="myUL">
 <c:forEach var="userBean" items="${list}">   
<li><a href="#">${userBean.username}</a></li>
</c:forEach>  
</ul>

实际上,它会执行,但最后一条记录仅显示在JSP中

这是我的MySQL记录

 username
    james
    smith
    william
    candy

    Now output comes 
    username
    candy
    candy
    candy
    candy
Anyone correct my code

2 个答案:

答案 0 :(得分:0)

您在方法getData中遇到问题。请参考以下代码:

public List<Tenant> findAll() {

        List<Tenant> result = jdbcTemplate.query(
                "SELECT id, name, email, created_date FROM tenant",
                (rs, rowNum) -> new Tenant(rs.getInt("id"),
                        rs.getString("name"), rs.getString("email"), rs.getDate("created_date"))
        );

        return result;

    }

我在教程Spring Boot Jdbc Mysql Example

中找到了它

希望获得帮助。

答案 1 :(得分:0)

DAO代码......

public List<UserBean> getdata()  {
List<UserBean> users = null;

    users = jdbcTemplate.query("select username from customer", new ResultSetExtractor<List<UserBean>>() {

        @Override
        public List<UserBean> extractData(ResultSet rs) throws SQLException, DataAccessException {
            List<String> usersTemp = new ArrayList<>();
            while(rs.next()) {
                UserBean ub = new UserBean();
                ub.setUsername(rs.getString(1));
                usersTemp.add(ub);
            }
            return usersTemp;
        }
    });
    return users;

}