Spring_Boot专栏 | ||
---|---|---|
上一篇 | 主目录 | 下一篇 |
【前言】
请求域共享就是:浏览器发送请求,服务器进行处理之后,得到了处理的结果,这些处理的结果如何给其他的部件共享呢?答案是将结果放到请求域进行共享。
如何将资源放到请求域
方式一:Model
在方法中加入参数Model model,在方法体中设置
model.addAttribute(“资源名称”,资源内容);
例如:
在控制器类EmployeeController中的一个查询所有员工的方法:
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
//查询员工列表
@GetMapping("/emps")
public String list(Model model){//Map或ModelMap
Collection<Employee> employees = employeeDao.getAll();
//放在请求域共享
model.addAttribute("emps",employees);
//thymeleaf默认拼串,classpath/templates/+return的字符串+.html
return "emp/list";
}
}
//放在请求域共享
model.addAttribute(“emps”,employees);
这样得到的employees就被放到了请求域emps变量中,其他的组件可以通过以下方法引用:
方法一:
@RequestParam(“emps”)
方法二
在html页面中
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}==0?'女':'男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
<td>
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
</td>
</tr>
方式二:Map
在方法中加入参数Map map,
@PostMapping(value = "/emp/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map){
if(!StringUtils.isEmpty(username) && "123456".equals(password)){//登录成功
return "dashboard";
}else {//登陆失败
map.put("msg","用户名或密码错误!");
return "login";
}
}
<p style="color: #ff0000" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
方式三:ModelMap
在方法中加入参数ModelMap modelMap,