还是写在前面:对于一些大牛来说这篇文章可能灌水严重,但本人是出于记录以及回忆之前知识的目的写下的此片文章,排版问题,内容有误请各位佬指正
css/js样式丢失
原因:使用
th:include时只能单纯引入th:fragment内的HTML格式,无法连同其CSS样式一起引入。也就是说与这个th:fragment所在HTML文件引入了何种CSS/JS无关
解决方法:
直接将<link />放入th:fragment所在标签下,如此link样式也可以被引用,JS同理
在同一页面利用th:replace引入不同页面资源时产生的EL1007E: Property or field 'name' cannot be found on null报错问题
程序框架如下:
Controller
@Controller
public class MainControl {
@Autowired
SingerService singerService;
@Autowired
SongService songService;
@GetMapping("/index")
String index( Model model){
SongQueryParam songQueryParam = new SongQueryParam();
songQueryParam.setPageNum(1);
songQueryParam.setPageSize(1);
List<Singer> singers = new ArrayList<>();
Singer singer = singerService.get("16427");
// singers.add(singer);
model.addAttribute("singers",singer);
model.addAttribute("songList",songService.list(songQueryParam));
return "homePage";
}
@GetMapping("/player")
String player(Model model){
SongQueryParam songQueryParam = new SongQueryParam();
songQueryParam.setPageSize(1);
songQueryParam.setPageNum(1);
List<Song> songList = songService.list(songQueryParam).getContent();
model.addAttribute("songList",songList);
return "player";
}
}
homepage.html
<div class="main" th:fragment="content">
<span th:text="${songList}"></span>
<!-- <th:block th:if="${singers != null}">-->
<span th:text="${singers.avatar}"></span>
<span th:text="${singers.name}"></span>
<!-- </th:block>-->
......
</div>
player.html
<div th:fragment="content">
<ul th:each="song,it:${songList}">
<li>
<p th:text="${it.count}"></p>
<p th:text="|name:${song.name}|"></p>
<p th:text="|url:${song.url}|"></p>
</li>
</ul>
访问http://127.0.0.1:8080/index:
上部分为${songList}、${singers.avatar}、${singers.name}资源显示
下部分为${it.count}、${song.name}、${song.url}资源显示
访问http://127.0.0.1:8080/player:
发现报错
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'avatar' cannot be found on null
当将homepage.html的singers资源注释时
<div class="main" th:fragment="content">
<span th:text="${songList}"></span>
<!-- <th:block th:if="${singers != null}">-->
<!-- <span th:text="${singers.avatar}"></span>-->
<!-- <span th:text="${singers.name}"></span>-->
<!-- </th:block>-->
......
</div>
再次访问http://127.0.0.1:8080/player页面,资源请求成功
- 当访问
http://127.0.0.1:8080/index时,程序只执行以下语句
model.addAttribute("singers",singer);
model.addAttribute("songList",songService.list(songQueryParam));
因此单纯访问http://127.0.0.1:8080/index并不会产生对象资源为空的错误
-
访问
http://127.0.0.1:8080/player时,程序只执行一下语句model.addAttribute("songList",songList);
此时singers资源并未被加载进来,因此报错对象资源为空
为何在访问http://127.0.0.1:8080/index时player.html中下列资源能成功请求
<ul th:each="song,it:${songList}">
<li>
<p th:text="${it.count}"></p>
<p th:text="|name:${song.name}|"></p>
<p th:text="|url:${song.url}|"></p>
</li>
</ul>
因为在/index中
model.addAttribute("songList",songService.list(songQueryParam));碰巧与/player中的资源songlist同名,将改为不同名称后便不会出现此问题
有关图片防盗链的解决
参考文章:解决图片防盗链的问题