做毕设(一)——thymeleaf取值

来源:互联网 发布:mac 免费vnc客户端 编辑:程序博客网 时间:2024/05/24 01:16

从零开始做一个有推荐算法的新闻网站
先设计个简单的表,包括用户表,新闻表,新闻类型表,评论表。
用spring-boot快速搭个框架。
用thymeleaf做前后端分离。
配置一下。
先实现一下简单的从数据库拿数据到页面展示。

<!--主页--><div th:each="n : ${News}">        <h1 th:text="${n.title}">标题</h1>    </div>
@Controller@RequestMapping("")public class NewsController {    @Autowired    NewsService newsService;    @RequestMapping(value = "",method = RequestMethod.GET)    public String showNews(ModelMap map) {        List<News> list = newsService.findAll();        Collections.reverse(list);//倒序新闻        map.addAttribute("News",list);        return "index";    }}

获得新闻列表,倒一下让新的新闻在上面。
之后做新闻的链接。

<!--新闻页--><table>    <h1 th:text="${n.title}">标题</h1>    <h5 th:text="${n.publicationdate}">时间</h5>    <h5 th:text="${n.author}">作者</h5>    <p th:text="${n.context}">内容</p></table>

把主页的新闻用超链接包起来

<a th:href="@{'/'+${n.id}}"><h1 th:text="${n.title}">标题</h1>

注意“/”会让字符转义,所以用+号连接。这样便可以根据id跳转。

@RequestMapping(value = "/{id}",method = RequestMethod.GET)    public String toNewsById(@PathVariable("id") String id,ModelMap map){        map.addAttribute("n",newsService.getNewsById(Integer.valueOf(id)));        return "newspage";    }

@PathVariable 可以获取url的参数。
以上其实花了我两天的时间,因为是第一次做,很多问题都要去查,不容易啊。

原创粉丝点击