亲宝软件园·资讯

展开

SpringMVC RESTFul实体类环境

把苹果咬哭的测试笔记 人气:0

一、搭建 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 中实现了几个增删改查的操作,代替与数据库的交互:

四、准备控制器

controller 包下新建 EmployeeController 类:

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
}

接下来就可以一个个的实现功能了,大概有:

访问首页查询全部数据删除跳转到添加数据页面执行保存跳转到更新数据页面执行更新

感谢《尚硅谷》的学习资源。

加载全部内容

相关教程
猜你喜欢
用户评论