Spring Boot显示数据表数据
Spring Boot网页显示数据表
配置数据库
①导入依赖 mybatis-plus。自动配置数据源
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>
mybatis-plus-boot-starter
</artifactId>
<version>3.4.1</version>
</dependency>
②配置yaml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: gcs
password: 273869
driver-class-name: com.mysql.cj.jdbc.Driver
配置Mapper接口
①创建Mapper接口
/**
* 继承BaseMapper就有操作数据库的方法,不需要写Mapper.xml
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
②创建与数据表对应的资源类
@Data
@Component
@ToString
@NoArgsConstructor
@AllArgsConstructor
@TableName("user_info")
public class User {
/**
* 所有属性都应该在数据表中除了有
*@TableField(exist = false)注释的
*/
//如果主键不是自增要添加
@TableId(type = IdType.AUTO)
private String username;
//被注释的说明表中没有该属性对应的字段
@TableField(exist = false)
private String password;
private String fullname;
private String email;
private String address;
private String city;
private String sex;
}
③创建服务接口和实现类
/**
* 继承IService<User>类,里面有所有的MySQL执行方法
*/
public interface UserService extends IService<User> {
}
/**
* 继承ServiceImpl<UserMapper,User>类就不需要重写
* IService接口里面的所有方法
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
④利用服务接口服务数据库获得数据
@Autowired
UserService userService;
@GetMapping("/dynamic_table.html")
public String dynamicTable(Model model)
{
//BaseMapper<>类中有很多操作数据库的方法
//所有继承了的类可以直接调用父类方法操作数据库
List<User> users = userService.list();
//将获得的数据用属性封装上传到网页上
model.addAttribute("users",users);
return "table/dynamic_table";
}
配置HTML文件
将网页的数据按表格形式显示
把users遍历获取user,再从user中获取属性值
<table class="display table table-bordered" id="hidden-table-info">
<thead>
<tr>
<th>username</th>
<th>fullname</th>
<th>email</th>
<th>address</th>
<th>city</th>
<th>sex</th>
</tr>
</thead>
<tbody>
<tr class="gradeX" th:each="user:${users}">
<td th:text="${user.username}">username</td>
<td th:text="${user.fullname}">fullname</td>
<td th:text="${user.email}">email</td>
<td th:text="${user.address}">address</td>
<td th:text="${user.city}">city</td>
<td th:text="${user.sex}">sex</td>
</tr>
</tbody>
</table>

浙公网安备 33010602011771号