说明:

本项目是在

https://blog.csdn.net/weixin_59334478/article/details/126749179?spm=1001.2014.3001.5501icon-default.png?t=M85Bhttps://blog.csdn.net/weixin_59334478/article/details/126749179?spm=1001.2014.3001.5501

在springboot中使用thymeleaf循环

springboot文章23

修改而来

pom.xml文件,核心配置文件等文件,与文章23保持一致,本文只展示最新添加的文件,以减小文章冗余,更容易看出循环的使用方法。

知识点:

       模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由 #号开始引用,我们比较常用的内置对象。

#request 表示 HttpServletRequest

#session 表示 HttpSession对象

session 表示Map对象的, 是#session的简单表示方式, 用来获取session中指定的key的值

​               #session.getAttribute("loginname") == session.loginname

这些是内置对象,可以在模板文件中直接使用。

1.index.html添加连接语句

2.ThymeleafController类添加方法

    //模板内置对象
    @GetMapping("/baseObject")
    public String baseObject(Model model, HttpServletRequest request,
                             HttpSession session){
        //添加数据
        model.addAttribute("myname","小明");
        request.setAttribute("requestData","request作用域中的数据");
        request.getSession().setAttribute("sessionData","session作用域中的数据");
        //直接使用session
        session.setAttribute("loginname","zhanshan");
        return "baseObject";
    }

 

3.创建inline的html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>模板的内置对象,方便使用request,session</title>
</head>
<body>
        <div style="margin-left: 300px">
            <h3>内置对象#request,#session,session的使用</h3>
            <p>获取作用域中的数据</p>
            <p th:text="${#request.getAttribute('requestData')}"></p>
            <p th:text="${#session.getAttribute('sessionData')}"></p>
            <p>session对象的直接使用可以直接session.key的值,而不用session.getAttribute()</p>
            <p th:text="${session.loginname}"></p>

            <br/>
            <br/>
            <h3>使用内置对象的方法</h3>
            getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/>
            getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/>
            getQueryString=<span th:text="${#request.getQueryString()}"></span><br/>
            getContextPath=<span th:text="${#request.getContextPath()}"></span><br/>
            getServerName=<span th:text="${#request.getServerName()}"></span><br/>
            getServerPort=<span th:text="${#request.getServerPort()}"></span><br/>
            <br/>
            <br/>
            session,getId=<span th:text="${#session.getId()}"></span>

        </div>

</body>
</html>

4.测试

 

 

 

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐