通過以前整合mybatis框架以後,本文繼續將springboot與springmvc進行整合.html
MVC設計模式將系統分爲了三部分:
控制器(Controller)- 負責獲取請求,處理請求,響應結果;
模型(Model) - 實現業務邏輯,數據邏輯實現;
視圖(View) - UI設計人員進行圖形界面設計,負責實現與用戶交互;前端
MVC的首要職責:是讓每一個對象各司其職,各盡所能;
其次是:基於"高內聚,低耦合"的面向接口思想實現相關層與層對象之間的交互.spring
首先須要添加springmvc依賴:
右鍵pom.xml-->spring-->Edit Starters-->搜索spring WEB以及Thymeleaf,並將這兩個依賴添加.後端
Web依賴提供了Spring MVC核心API,同時會嵌入一個Tomcat服務器;
Thymeleaf依賴提供了一個視圖解析器對象以及數據綁定機制.
Thymeleaf是一個html模板引擎,提供了與Spring MVC進行整合的API,可做爲MVC架構中Web應用的View層(已經逐步替代JSP進行使用).設計模式
須要在application.properties配置文件中添加視圖解析器配置(假如沒有配置也會默認配置,在默認配置中prefix默認值爲classpath:/templates/,後綴默認爲.html)瀏覽器
#springthymeleaf spring.thymeleaf.prefix=classpath:/templates/pages/ spring.thymeleaf.suffix=.html
在這裏咱們配置如上圖所示.tomcat
注意:根據配置,咱們須要在src/main/resources目錄下建立templates/pages目錄.springboot
thymeleaf目錄下的html文件(模板文件)沒法直接訪問,若要直接訪問須要在src/main/resources目錄下建立static目錄(用於存儲靜態資源).服務器
代碼以下:mybatis
@Controller @RequestMapping("/goods/") public class GoodsController { @RequestMapping("doGoodsUI") public String doGoodsUI() { return "goods"; } }
經過添加@Controller註解將其交給spring管理,雖然是@Controller,但其實他並不屬於MVC設計模式中的"C",而是Handler(處理器),可理解爲一個後端控制器,但屬於"M".
該方法是由前端控制器DispatcherServlet調用,返回值也是返回給前端控制器;返回值會被前端控制器調用視圖解析器添加先後綴.
因爲GoodsController類最後會return "goods";因此咱們須要在/templates/pages/目錄下建立goods.html文件.
那麼當GoodsController類中return時,視圖解析器會經過咱們所配置的先後綴,將其指向/templates/pages/目錄下的goods.html文件,在網頁中進行顯示.
打開服務器(內嵌的tomcat),打開瀏覽器輸入路徑進行訪問測試
#server server.port=80
因爲我將端口號改成了80,因此只需在瀏覽器輸入:
localhost/goods/doGoodsUI便可成功訪問.
既然已經能夠成功訪問後,能夠與以前的Dao層的數據操做一同使用一下,看一下效果,這裏以查詢全部商品爲實例.
@Controller @RequestMapping("/goods/") public class GoodsController { @Autowired private GoodsService goodsService; @RequestMapping("doGoodsUI") public String doGoodsUI(Model model) { List<Goods> list = goodsService.findObjects(); model.addAttribute("list", list); return "goods"; } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>the goods pages</h1> <table> <thead> <tr> <th>id</th> <th>name</th> <th>remark</th> <th>createdTime</th> </tr> </thead> <tbody> <tr th:each="g:${list}"> <td th:text="${g.id}">1</td> <td th:text="${g.name}">pathon</td> <td th:text="${g.remark}">framwork</td> <td th:text="${#dates.format(g.createdTime, 'yyyy/MM/dd HH:mm:ss')}">2020/8/3 17:33</td> </tr> </tbody> </table> </body> </html>
@Mapper public interface GoodsDao { @Select("select * from tb_goods") public List<Goods> findObjects(); }
public interface GoodsService { public List<Goods> findObjects(); }
@Service public class GoodsServiceImpl implements GoodsService{ @Autowired private GoodsDao goodsDao; @Override public List<Goods> findObjects() { long t1=System.currentTimeMillis(); List<Goods> list = goodsDao.findObjects(); long t2=System.currentTimeMillis(); log.info("execute time:{}",(t2-t1)); return list; } }
以上是代碼實現,能夠獲得正確顯示: