首先,搭建项目,引入自己需要的jar,由于需要html展示,所以我加了一个thymelea模板引擎,这个可以不要。
这里需要注意几点:
1、dao层需要加入@Mapper 注解,或者在启动类中加@MapperScan("com.xh.demo.dao"),主要是为了映射mapper
2、mapper.xml需要放到resources下面,不然无法找到
application.properties配置文件
#数据源配置
spring.datasource.url=jdbc:mysql://localhost/mysql_test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#thymelea
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#公共资源路径指向
mybatis.typeAliasesPackage= com.xh.demo
mybatis.mapperLocations= classpath:mapper/*.xml
controller
@RestController
@RequestMapping(value="book", produces = {"application/json;charset=UTF-8"})
public class BookController {
@Resource
private BookDao bookDao;
@ResponseBody
@RequestMapping(value="/query")
public ModelAndView query(ModelAndView mv) {
mv.setViewName("/index");
List<BookEntity> books = bookDao.query();
mv.addObject("books", books);
return mv;
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td>编号</td>
<td>书名</td>
<td>作者</td>
<td>出版社</td>
<td>价格</td>
</tr>
<tr th:each="book : ${books}">
<td th:text="${book.bookNo}"></td>
<td th:text="${book.bookName}"></td>
<td th:text="${book.bookAdmin}"></td>
<td th:text="${book.bookPress}"></td>
<td th:text="${book.bookPrice}"></td>
</tr>
</table>
</body>
</html>
实现效果
最后,祝你们成功!