前言
- spring boot : 2.0.0.RELEASE
- maven
- eclipse
- thymeleaf 3.0
- 某些情况下需要在HTML中调用Service。比如:做CMS系统时提供的随时获取文章的功能。
解决办法
使用thymeleaf提供的调用Spring Bean的方法。
Access any beans in your application context using SpringEL’s syntax: ${@myBean.doSomething()}
注:很贴心的功能啊。
实操
编写Bean
这里不赘述了。确定好要编写什么样的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 {
@Autowired
ChannelEntityRespository channelEntityRespository;
@Override
public 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>