一、搭建 mvc 环境
新建一个 module 模块,创建 maven 工程,步骤跟以前一样,各种配置文件内容也可以拷贝修改一下即可。
二、创建实体类
新建个 bean 包,创建实体类 Employee:
package com.pingguo.rest.bean;
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Employee(Integer id, String lastName, String email, Integer gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Employee() {
}
}
三、准备 dao 模拟数据
新建一个 dao 包,创建 EmployeeDao 类,这里不使用数据库,直接存放一些静态数据:
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 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<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
dao 中实现了几个增删改查的操作,代替与数据库的交互:
map集合
employees,里存放了 5 个 Employee 对象。save()
方法是保存,包含了添加操作和修改操作。getAll()
是查询所有,返回的是所有 Employee 对象的 value。get()
是查询单个员工信息,根据 id 。delete()
是根据 id 删除数据。
四、准备控制器
controller 包下新建 EmployeeController 类:
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
}
感谢《尚硅谷》的学习资源。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。