Spring MVC如何实现查询结果与搜索表单在同一JSP页面展示
修改方案
我们只需要合并两个JSP的逻辑到同一个页面,同时调整Controller统一返回该页面,通过Model传递的参数控制展示内容即可,具体修改如下:
1. 调整EmpController代码
修改逻辑为:无论是否查询到结果,都统一返回搜索表单所在的index.jsp,同时将查询结果、查询标记、用户输入的日期参数存入Model供页面使用:
@Controller public class EmpController { @Autowired EmpDao dao; @PostMapping("/viewemp") public String viewemp(@RequestParam(value="start") @DateTimeFormat(pattern="yyyy-MM-dd") Date start, @RequestParam(value="end") @DateTimeFormat(pattern="yyyy-MM-dd") Date end, Model m){ List<Event> list=dao.getEmployees(start,end); // 传递查询结果 m.addAttribute("list",list); // 标记用户已提交查询 m.addAttribute("hasSearched", true); // 回显用户输入的日期参数 m.addAttribute("start", start); m.addAttribute("end", end); // 统一返回表单页面 return "index"; } }
2. 合并修改index.jsp代码
把原结果页的标签引用、展示逻辑合并到表单页中,增加JSTL判断控制结果区域的展示:
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <center> <h1> Search Event</h1> <form method="post" action="viewemp"> Start Date: <input type="date" id="start" name="start" value="${start}"/> End Date: <input type="date" id="end" name="end" value="${end}"/> <input type="submit" value="find" /> </form> <!-- 动态结果展示区域 --> <c:if test="${hasSearched}"> <c:choose> <%-- 有查询结果时渲染表格 --%> <c:when test="${not empty list}"> <h1>Event List</h1> <table border="2" width="70%" cellpadding="2"> <tr> <th>eventName</th> <th>eventOrgName</th> <th>eventFare</th> <th>startDate</th> <th>endDate</th> </tr> <c:forEach var="emp" items="${list}"> <tr> <td>${emp.eventName}</td> <td>${emp.eventOrgName}</td> <td>${emp.eventFare}</td> <td>${emp.startDate}</td> <td>${emp.endDate}</td> </tr> </c:forEach> </table> </c:when> <%-- 无查询结果时显示提示 --%> <c:otherwise> <p style="color: #ff3333; margin-top: 20px;">* 未查询到符合条件的事件记录</p> </c:otherwise> </c:choose> </c:if> </center> <br/>
实现逻辑说明:
- 用户首次访问页面时,
hasSearched参数不存在,仅展示搜索表单 - 用户提交查询后,
hasSearched为true,根据查询结果动态展示表格或无数据提示 - 表单增加了日期回显逻辑,用户提交后输入的日期不会清空,体验更友好
内容的提问来源于stack exchange,提问作者Sourav Pal
相关产品推荐
相关产品推荐

