目录
7、RESTful案例
7.1、准备工作
7.1.1、准备实体类
7.1.2、准备到模拟数据
7.2、功能清单
7.3、访问首页
7.3.1、配置view-controller
7.3.2、创建页面
7.4、查询所有员工信息
7.4.1、控制器方法
7.4.2、创建employee_list.html
7.5、删除
7.5.1、创建处理delete请求方式的表单
7.5.2、控制器方法
7.6、跳转到添加数据页面
7.6.1、配置view-controller
7.6.2、创建employee_add.html
7.7、执行保存
7.8、跳转到更新数据页面
7.8.1、控制器方法
7.8.2、创建employee_update.html
7.9、执行更新
和传统的CRUD一样,实现对员工信息的增删查改
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
//省略getter/setter方法和有参、无参构造方法
}
@Repository
public class EmployeeDao {
private static Map employees = null;
static{
employees = new HashMap();
employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
}
private static Integer initId = 1006;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employees.put(employee.getId(), employee);
}
public Collection getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
功能 | URL地址 | 请求方式 |
---|---|---|
访问首页 | / | get |
查询全部数据 | /employee | get |
删除 | /employee/2 | delete |
跳转到添加数据页面 | /toAdd | get |
执行保存 | /employee | post |
跳转到更新页面 | /employee/2 | get |
执行更新 | /employee | put |
首页
index.html
查询所有的用户信息
查询id为1的用户信息
查询所有的员工信息
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getAllEmployee(Model model){
//获取所有的员工信息
Collection allEmployee = employeeDao.getAll();
//将所有的员工信息在请求域中共享
model.addAttribute("allEmployee", allEmployee);
//跳转到列表页面
return "employee_list";
}
employee list
@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
//删除员工信息
employeeDao.delete(id);
//重定向到列表功能:/employee
return "redirect:/employee";
}
add employee
控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
//保存员工信息
employeeDao.save(employee);
//重定向到列表功能:/employee
return "redirect:/employee";
}
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String toUpdate(@PathVariable("id") Integer id, Model model){
//根据id查询员工信息
Employee employee = employeeDao.get(id);
//将员工信息共享到请求域中
model.addAttribute("employee", employee);
//跳转到employee_update.html
return "employee_update";
}
update employee
控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
//修改员工信息
employeeDao.save(employee);
//重定向到列表功能:/employee
return "redirect:/employee";
}