You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 16:06:00