单一精确搜索功能(By Id)的拉垮实现,记录一下,菜鸡独自秃头
基本流程
员工管理(emps)页添加“搜索”按钮,点击跳转到search页面(一个表单),输入ID查询,由result页面显示搜索结果,么了。
代码改动
list.html(add)
加个按钮
<h2>
<a class="btn btn-sm btn-success" th:href="@{/emp}">添加员工</a>
<a class="btn btn-sm btn-success" th:href="@{/search}">搜索</a>
</h2>
search.html(new)
直接拿add.html删改,区别只在“main”部分
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<form th:action="@{/result}" method="post" >
<div class="form-group" ><label>id</label>
<input class="form-control"
placeholder="kuangshen"
type="text"
name="id">
</div>
<button class="btn btn-primary"
onclick="return isf()"
type="submit">搜索
</button>
<a class="btn btn-secondary" th:href="@{/emps}">取消</a>
</form>
</main>
myresult.html(new)
跟list.html一样并且同目录下(貌似写好EmployeeController就可以不要这个页面)
EmployeeService.java(add)
//通过ID查询员工
public Employee getEmployeeById(Integer id){
return employeeMapper.getEmployeeById(id);
}
//getAll变种,因为用上面那个返回的Employee对象部门名为"null",所以写了这个尝试
public Collection<Employee> getAllByID(Integer id){
return employeeMapper.getAllByID(id);
}
EmployeeMapper.java(add)
Employee getEmployeeById(Integer id);
//参数不能少
Collection<Employee> getAllByID(Integer id);
EmployeeMapper.xml(add)
<!--根据getAll写的后面两个,SQL不会用-->
<select id="getAll" resultMap="EmployeeResultMap">
SELECT * FROM employee,department WHERE employee.departmentId=department.id
</select>
<select id="getEmployeeById" parameterType="int" resultMap="EmployeeResultMap">
SELECT * FROM employee WHERE id=#{id}
</select>
<!--双条件-->
<select id="getAllByID" resultMap="EmployeeResultMap">
SELECT * FROM employee,department
WHERE employee.departmentId=department.id AND employee.id=#{id}
</select>
EmployeeController.java(add)
//冗余请求,为了进search而写了一个tosearch
@RequestMapping("/search")
public String tosearch( Model model){
// Collection<Department> departments = departmentService.getDepartments();
// System.out.println(departments);
// model.addAttribute("departments",departments);
return "emp/search";
}
//遇事不决,就打印出来看看
@PostMapping("/result")
public String result(@RequestParam(name="id")Integer id,Model model){
//首先是能从前端拿到数据
System.out.println("get====>"+id);
//然后这个搜索出来的结果中Department(id=101, departmentName=null),有部门id 没部门名
Employee employee=employeeService.getEmployeeById(id);
System.out.println(employee);
//接着这个没问题,Department(id=101, departmentName=教学部)
Collection<Employee> employees = employeeService.getAllByID(id);
System.out.println(employees);
//给前端返回数据
model.addAttribute("emps",employees);
// model.addAttribute("emps",employee);
return "emp/myresult";
}
运行测试
顶栏(topbar)弄不出来搜索,干脆多来点跳转,现在想想还不如花时间学Html5和thymeleaf