在这种模板开发框架里面是不提倡使用内置对象的,但是很多的开发者依然需要使用内置对象进行处理,
所以下面来看下如何在页面中采用内置对象的方式完成.
1. 在控制器里面追加一个方法, 这个方法将采用内置对象的形式传递属性.
@RequestMapping(value = "/message/inner", method = RequestMethod.GET)
public String inner(HttpServletRequest request, Model model) {
model.addAttribute("url", "www.baidu.cn");
return "message/message_show_inner";
}
其中model传递的本质就属于request属性范围.
2、编写页面进行内容的显示:
message_show_inner.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模板渲染</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico" />
<meta http-equiv="Content-Type" content="text/html;charse=UTF-8">
</head>
<body>
<p th:text="'官方网站:' + ${url}">
</body>
</html>
而后此时也可以使用"*{属性名称}"进行访问:
<p th:text="'官方网站:' + *{url}">
<p th:text="'用户名:' + *{requestMessage}">
官方网站:www.baidu.cn
用户名:springboot-request
3、修改程序现在传递三种属性范围:
@RequestMapping(value = "/message/inner", method = RequestMethod.GET)
public String inner(HttpServletRequest request, Model model) {
request.setAttribute("requestMessage", "springboot-request");
request.getSession().setAttribute("sessionMessage", "springboot-session");
request.getServletContext().setAttribute("applicationMessage",
"springboot-application");
model.addAttribute("url", "www.baidu.cn");
request.setAttribute("url2",
"<span style='color:red'>www.baidu.cn</span>");
return "message/message_show_inner";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模板渲染</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico" />
<meta http-equiv="Content-Type" content="text/html;charse=UTF-8">
</head>
<body>
<p th:text="${#httpServletRequest.getRemoteAddr()}"/>
<p th:text="${#httpServletRequest.getAttribute('requestMessage')}"/>
<p th:text="${#httpSession.getId()}"/>
<p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}"/>
<hr/>
<p th:text="'sessionMessage = ' + ${sessionMessage}"/>
<p th:text="'applicationMessage = ' + ${applicationMessage}"/>
<p th:text="'requestMessage = ' + ${requestMessage}"/>
<p th:text="'sessionMessage = ' + ${session.sessionMessage}"/>
<p th:text="'applicationMessage = ' + ${application.applicationMessage}"/>
</body>
</html>
4、而后在页面之中如果想要访问不同属性范围中的内容,则可以采用如下的做法完成:
<p th:text="'requestMessage = ' + ${requestMessage}"/>
<p th:text="'sessionMessage = ' + ${session.sessionMessage}"/>
<p th:text="'applicationMessage = ' + ${application.applicationMessage}"/>
thymeleaf 考虑到了实际的开发情况,因为 request 传递属性是最为常用的,但是 session 也有可能
使用,例如:用户登录之后需要显示用户 id,那么就一定要使用到 session,所以现在必须增加属性范围的
形式后才能够正常使用。在 thymeleaf 里面也支持有 JSP 内置对象的获取操作,不过一般很少这样使用。
<p th:text="${#httpServletRequest.getRemoteAddr()}"/>
<p th:text="${#httpServletRequest.getAttribute('requestMessage')}"/>
<p th:text="${#httpSession.getId()}"/>
<p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}"/>
现在会将所有可能显示出的内容全部重新做了一个模板的重新的改写.