1.数据库准备
建好需要的表,这里我的表是info_list
2.文件创建
实体类Info
public class Info {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Info{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Dao层InfoDao
@Mapper
@Component(value = "infoDao")
public interface InfoDao {
List<Info> findAll();
}
mybatis的mapper
InfoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.learn.Dao.InfoDao">
<select id="findAll" resultType="com.example.learn.Entity.Info">
select * from info_list;
</select>
</mapper>
Service层
InfoService
public interface InfoService {
public List<Info> getAll();
}
实现层
InfoServiceImpl
@Service("InfoService")
public class InfoServiceImpl implements InfoService {
@Autowired
private InfoDao infoDao;
@Override
public List<Info> getAll() {
return infoDao.findAll();
}
}
Controller层
InfoController
@Controller
public class InfoController {
@Autowired
private InfoService infoService;
@RequestMapping("/testList")
public String getAll(Model model){
List<Info> info=infoService.getAll();
model.addAttribute("info",info);
return "testList";//返回页面
}
}
页面
testList.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>name</th>
</tr>
<tr th:each="info1:${info}">
<td th:text="${info1.id}"></td>
<td th:text="${info1.name}"></td>
</tr>
</table>
</body>
</html>
运行结果(地址输入的testList是Controller层定义的)