1:
Html文件加上
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
2:
Controller写
@GetMapping("/")//访问首页时
public String index(Model model,
@RequestParam(name = "page", defaultValue = "1") Integer page,
@RequestParam(name = "size", defaultValue = "10") Integer size,
@RequestParam(name = "search", required = false) String search,
@RequestParam(name = "tag", required = false) String tag,
@RequestParam(name = "creator", required = false) Long creator,
@RequestParam(name = "sort", required = false) String sort) {
PaginationDTO pagination = newsService.list(search, tag, creator, sort, page, size);
List<String> tags = hotTagCache.getHots();
model.addAttribute("pagination", pagination);
model.addAttribute("search", search);
model.addAttribute("tag", tag);
model.addAttribute("tags", tags);
model.addAttribute("creator", creator);
model.addAttribute("sort", sort);
return "index";
}
getmapping/postmapping以及后面的网址,该写什么不多说。
@RequestParam/@PathVariable
地址1:http://localhost:8989/SSSP/emps?pageNo=2
地址2:http://localhost:8989/SSSP/emp/7
如果想获取地址1中的 pageNo的值 ‘2’ ,则使用 @RequestParam ,
如果想获取地址2中的 emp/7 中的 ‘7 ’ 则使用 @PathVariable
(其中defaultValue是默认值)
PaginationDTO pagination = newsService.list(search, tag, creator, sort, page, size);
我是比如前端点搜索,按标签查看等等,都用这个。比如传个网址http://localhost:8080/?page=1&search=&tag=疫情&creator=&sort=
就是第一页,搜tag是疫情的。其他都每填,传到后端用这个service里的list方法。里面有mapper(dao)查询出来,再返回出值(paganition)
model.addAttribute("pagination", pagination);。这些(第一个参数是前端看到的,第二个是后端你的命名的名字)。比如我想在前端显示你搜索的tag是“xxx”。那前端就写tag就行。显示你搜索的内容是“xxx”。那前端就写search就行。
3.前端
Th:开头常用的大概有
th:text
<span th:text="${news.user.name}"></span>
比如我前端是model.addAttribute("news", news);
那这样就能以文本显示news的用户的名字。
th:href="@{'/publish/'+${news.id}
跳转到/publish/这个连接再拼接上news的id。就是publish/123,然后后端就能@PostMapping("/publish")
4.
以增加为例
前端form表单
《form action="/publish" method="post">
<input type="hidden" name="id" th:value="${id}">
Action是"/publish"
或者th:action="@{'/deltag/'+${tag}}" 也行,这里的tag就是之前model传来的。
method="post,不多说
th:value="${id}“,表示你要增加id,(要是删除的话直接value=”delete就行,不用th
到后端public String doPublish(
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "content", required = false) String content,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "id", required = false) Long id,
前三行不说了,一样的,@RequestParam(value = "id", required = false) Long id,得到前端传来的id,然后
newsService.createOrUpdate(news);
return "redirect:/";
去service;里mapper保存/更新。然后跳转到首页
5.th还有th:if="${news.id!=null},就可以比如news的id不为空时才怎么样,比如为空就不显示一个按钮,不为空就显示什么的,还有th:each循环,th:class