从数据库中取数据并在页面显示,客户端(浏览器)出发一个request到contorller,controller通过selectALL或者其他查询方式取到list,通过request.setAttribute再传给前端页面,例如
@RequestMapping(value = "/employees")
public String getAllEmployee(HttpServletRequest request){
List<Employee> employees = employeeService.selectAll();
request.setAttribute( "list",employees);
return "employee";
}
前端页面employee.jsp通过request.getAttribute方法接受到list,如下
<%List<Employee> list = (List<Employee>) request.getAttribute("list");%>
然后对list对象循环遍历,显示在前端页面
从前台页面存数据到数据库,比如通过form表单存数据,用input标签实现,form的提交按钮最好也用input标签,不要用button标签,因为如果在 HTML 表单中使用 button标签,不同的浏览器可能会提交不同的按钮值。
在增加数据的Controller里,为了避免转发(forward)引起的刷新后多次执行插入数据的操作,我们可以使用重定向来解决(redirect).
因为浏览器刷新会执行上一步操作,转发操作浏览器并不知道,是服务器内部的处理,所以刷新后还会执行浏览器发出的request,并且带有之前的数据。
如果使用重定向,浏览器就会知道多了一步操作,刷新的时候执行上一步操作的时候就不会执行之前提交的request。