如何使用Spring Boot实现员工数据搜索功能
Spring Boot员工搜索功能修复方案
你现有代码存在三处核心不匹配问题,按以下步骤修改即可实现预期效果:
1. 修正index.html代码
删除多余的id隐藏域,避免参数冲突,修正后代码如下:
<form action="#" th:action="@{/search}" th:object="${employee}" method="post"> <div align="left"> <tr> <label class="form-label" >Employee ID</label> <td> <input type="text" th:field="*{id}" class="form-control" placeholder="Employee ID" /> </td> </tr> </div> <br> <tr> <td colspan="2"><button type="submit" class="btn btn-info">Search</button> </td> </tr> <div align="left"> <tr> <label class="form-label" >Employee Name</label> <td> <input type="text" th:field="*{ename}" class="form-control" placeholder="Employee Name" /> </td> </tr> </div> </form>
注:你原有代码里div的属性拼写错误
alight,已修正为align,不影响功能可以不改。
2. 修正Controller层代码
原有搜索接口是路径变量传参、返回new视图,和前端表单提交逻辑不匹配,替换原有搜索接口代码如下:
@Controller public class EmployeeController { @Autowired private EmployeeService service; @GetMapping("/") public String add(Model model) { List<Employee> listemployee = service.listAll(); model.addAttribute("employee", new Employee()); return "index"; } @PostMapping("/search") public String searchEmployee(@ModelAttribute("employee") Employee employeeParam, Model model) { Employee resultEmp = service.get(employeeParam.getId()); if(resultEmp != null) { model.addAttribute("employee", resultEmp); }else { // 未查询到对应员工时保留输入的id,姓名置空 employeeParam.setEname(""); model.addAttribute("employee", employeeParam); } return "index"; } }
3. 确认EmployeeService实现逻辑
确保Service层的get方法参数类型为Long(和实体类id类型匹配),示例实现:
public Employee get(Long id) { return employeeRepository.findById(id).orElse(null); }
原有Entity、Repository代码无需修改。
内容的提问来源于stack exchange,提问作者radu ba
相关产品推荐
相关产品推荐

