thymeleaf 内置对象操作

在这种模板开发框架里面是不提倡使用内置对象的,但是很多的开发者依然需要使用内置对象进行处理,所以下面来观察下如何在页面中采用内置对象的方式完成。

1.0 在控制器里面追加一个方法 这个方法将采用内置对象的形式传递属性

@RequestMapping(value = "/inner",method = RequestMethod.GET)
public String inner(HttpServletRequest request,Model model){
    request.setAttribute("msg","zwjava");
    model.addAttribute("url","www.zwjava.com");
    return  "message/message_show_inner";
}

其中 model 传递的本质就属于request 属性范围
2.0 编写页面进行内容的显示

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta  http-equiv="Content-Type"  content="text/html;charset=UTF-8" >
    <title>Title</title>
</head>
<body>
  <p th:utext="'url= '+${url}"></p>
   <!--/*@thymesVar id="msg" type="msg"*/-->
   <p th:utext="'msg ='+${msg}"></p>
</body>
</html>
  而后此时也可以使用 *{属性名称} 进行访问 <p th:utext="'url='+*{url}">;

3.0 修改程序现在传递三种属性范围

  @RequestMapping(value = "/inner",method = RequestMethod.GET)
public String inner(HttpServletRequest request,Model model){
    request.setAttribute("requestMessage","zwjava-request");
    request.getSession().setAttribute("sessionMessage","session.zwjava-session");
    request.getServletContext().setAttribute("applicationMessage","application.zwjava-application");
    model.addAttribute("url","www.baidu.com");
    request.setAttribute("url2","<span style='color:red'>www.baidu.com</span>");
    return  "message/message_show_inner";
}

4.0 在页面之中如果要想访问不同属性范围中的内容 则可以采用如下的做法完成

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta  http-equiv="Content-Type"  content="text/html;charset=UTF-8" >
    <title>Title</title>
</head>
<body>
<!--/*@thymesVar id="requestMessage" type=""*/-->
<p th:text="'requestMessage='+${requestMessage}"></p>
<!--/*@thymesVar id="sessionMessage" type="session.sessionMessage"*/-->
<p th:text="'sessionMessage='+${session.sessionMessage}"></p>
<!--/*@thymesVar id="application" type="application"*/-->
<p th:text="'applicationMessage='+${application.applicationMessage}"></p>
</body>
</html>

thymeleaf 考虑到了实际的开发情况 因为request 传递属性时最为常用的 但是Session 也有可能使用,列如用户登录之后需要显示用户id,那么就一定要使用到Session  所以现在必须增加属性范围的形式后才能够正常使用 。
5.0 实际上在thymeleaf 里面也支持有jsp 内置对象的获取操作 不过一般很少这样使用

<p th:text="${#httpServletRequest.getRemoteAddr()}"></p>
<p th:text="${#httpServletRequest.getAttribute(requestMessage)}"></p>
<p th:text="${#httpSession.getId()}"></p>
<p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}"></p>

githua  代码如下   https://github.com/zhouwei520/SpringbootDemo/tree/master/demo9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伟子涵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值