【thymeleaf】【SpringBoot】在HTML中调用Spring Bean
生活随笔
收集整理的這篇文章主要介紹了
【thymeleaf】【SpringBoot】在HTML中调用Spring Bean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
- spring boot : 2.0.0.RELEASE
- maven
- eclipse
- thymeleaf 3.0
- 某些情況下需要在HTML中調用Service。比如:做CMS系統(tǒng)時提供的隨時獲取文章的功能。
解決辦法
使用thymeleaf提供的調用Spring Bean的方法。
Access any beans in your application context using SpringEL’s syntax: ${@myBean.doSomething()}
注:很貼心的功能啊。
實操
編寫B(tài)ean
這里不贅述了。確定好要編寫什么樣的bean,編寫即可。
package myabc.weicms.fn.content; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import myabc.weicms.dao.ChannelEntity; import myabc.weicms.dao.ChannelEntityRespository;@Service("viewBean4Channel") public class ChannelService {@AutowiredChannelEntityRespository channelEntityRespository;@Overridepublic String toString() {return "My Name Is ChannelService! Bean Name Is viewBean4Channel!";}/* 這里查詢了數據庫。但是關注點不要放在查詢數據庫上。*/public List<ChannelEntity> getChannel() {Pageable pageable = PageRequest.of(0, 10, Sort.by(Direction.ASC, "id"));Page<ChannelEntity> pageData = this.channelEntityRespository.findAll(pageable);return pageData.getContent();} }HTML中調用Spring Bean
<h1>welcome by thymeleaf</h1><br /><ul><li th:text="${@viewBean4Content}">顯示點兒什么</li></ul><br /><h3>欄目列表</h3><table class="layui-table"><tbody><tr th:each="row : ${@viewBean4Channel.getChannel()}"><td th:text="${row.id}">1</td><td th:text="${row.name}">title</td></tr></tbody></table>運行結果
總結
以上是生活随笔為你收集整理的【thymeleaf】【SpringBoot】在HTML中调用Spring Bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【SpringBoot】项目实现热部署的
- 下一篇: 前端框架-后台模板:Xadmin