如何防止同一模型的多个实例

时间:2017-02-14 11:19:20

标签: java spring thymeleaf

我想知道如何防止Thymeleaf中同一模型的多个实例,例如:在标题上显示用户名。

<span th:text="${username}">User Name</span>

控制器:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
    model.addAttribute("username", "User Name");
    return "index.html";
}

@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String admin(Model model) {
    model.addAttribute("username", "User Name");
    return "indexAdmin.html";
}

@RequestMapping(value = "/page", method = RequestMethod.GET)
public String page(Model model) {
    model.addAttribute("username", "User Name");
    return "page.html";
}

1 个答案:

答案 0 :(得分:0)

Spring允许您执行以下操作:

<div id="map_outer" style="position: absolute; left: 3px; z-index: 1;">
<svg height="35" version="1.1" width="70" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
<defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
</defs>
<!--
<path fill="#cecece" stroke="#808080" d="M503.7,743.8C694,647.1999999999999,636.6,326.74999999999994,348.1,334.09V205.39L120.00000000000003,400.39L348.1,606.19V474.59000000000003C589,469.09000000000003,578,677.3900000000001,503.70000000000005,743.8900000000001Z" stroke-width="40" stroke-opacity="1" fill-opacity="1" transform="matrix(0.05,0,0,0.05,-1.9,-5.7)" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 1; fill-opacity: 1; cursor: pointer;">
</path>
-->
<path fill="#ffcc00" stroke="#808080" d="M 0 15 L 35 0 L 35 8 L 70 8 L 70 22 L 35 22 L 35 30 Z" stroke-width="0" stroke-opacity="1" fill-opacity="1" transform="matrix(0)" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 1; fill-opacity: 1; cursor: pointer;">
</path>
</svg>
</div>

此代码将为封闭控制器正在处理的每个请求设置“用户名”属性。您还可以访问几乎所有可用于@RequestMapping方法的参数,包括模型对象本身。

如上面的评论中所述,如果您希望在特定用户的请求之间保留一些对象(例如,从数据库中获取它并使用该实例填充模型),那么您可以创建一个@SessionAttributes处理程序或将其放入手动对象进入会话。

似乎可以从问题中删除“百里香”标签