REST风格CRUD(无持久化层)代码

在这里插入图片描述

pom.xml

 <dependencies>
        <!--spring-webmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- 导入thymeleaf与spring5的整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--CharacterEncodingFilter:处理POST请求乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--HiddenHttpMethodFilter:支持PUT或DELETE提交方式-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--DispatcherServlet:前端控制器-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
   <servlet-mapping>
       <servlet-name>DispatcherServlet</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvn="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--开启组件扫描-->
    <context:component-scan base-package="com.dudu"></context:component-scan>
    <!--装配ThymeleafViewResolver-->
    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="characterEncoding" value="UTF-8"></property>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="characterEncoding" value="UTF-8"></property>
                        <property name="prefix" value="/WEB-INF/pages/"></property>
                        <property name="suffix" value=".html"></property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--装配视图控制器-->
    <mvn:view-controller path="/" view-name="index"></mvn:view-controller>
    <!--装配Default-servlet-handler-->
    <mvn:default-servlet-handler></mvn:default-servlet-handler>
    <!--装配annotation-driven-->
    <mvn:annotation-driven></mvn:annotation-driven>
</beans>

EmployeeController

@Controller
public class EmployeeController {
    @Autowired
    @Qualifier("employeeDao")
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    //查询所有员工信息
    @GetMapping("emps")
    public String getAllEmps(Map<String,Object> map){
        Collection<Employee> employees = employeeDao.getAll();
        map.put("emps",employees);
        return "list";
    }
    //跳转添加页面
    @GetMapping("toAddPage")
    public String toAddPage(ModelMap modelMap){
        Collection<Department> depts = departmentDao.getDepartments();
        modelMap.addAttribute("depts",depts);
        return "addemp";
    }
    //实现员工添加并返回员工列表
    @PostMapping("emps")
    public String toList(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    //跳转员工修改页面
    @GetMapping("toUpdatPage/{id}")
    public String toUpdatPage(@PathVariable("id")Integer empId,Map<String,Object>map){
        Employee employee = employeeDao.get(empId);
        map.put("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("depts",departments);
        return "updateemp";
    }
    //实现员工修改并返回员工列表
    @PutMapping("emps")
    public String toUpdateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    //实现删除
    @DeleteMapping("emps/{id}")
    public String toDelete(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}

DepartmentDao

@Repository
public class DepartmentDao {
	private static Map<Integer, Department> departments = null;
	static{
		departments = new HashMap<Integer, Department>();
		
		departments.put(101, new Department(101, "D-AA"));
		departments.put(102, new Department(102, "D-BB"));
		departments.put(103, new Department(103, "D-CC"));
		departments.put(104, new Department(104, "D-DD"));
		departments.put(105, new Department(105, "D-EE"));
	}
	public Collection<Department> getDepartments(){
		return departments.values();
	}
	public Department getDepartment(Integer id){
		return departments.get(id);
	}
}

EmployeeDao

@Repository
public class EmployeeDao {
	private static Map<Integer, Employee> employees = null;
	@Autowired
	private DepartmentDao departmentDao;
	static{
		employees = new HashMap<Integer, Employee>();

		employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
		employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
		employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
		employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
		employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
	}
	private static Integer initId = 1006;
	public void save(Employee employee){
		if(employee.getId() == null){
			employee.setId(initId++);
		}
		employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
		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);
	}
}

Department

public class Department {
	private Integer id;
	private String departmentName;

	public Department() {
		// TODO Auto-generated constructor stub
	}
	public Department(int i, String string) {
		this.id = i;
		this.departmentName = string;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDepartmentName() {
		return departmentName;
	}
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	@Override
	public String toString() {
		return "Department [id=" + id + ", departmentName=" + departmentName
				+ "]";
	}
}

Employee

public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	//1 male, 0 female
	private Integer gender;
	private Department department;
	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 Department getDepartment() {
		return department;
	}
	public void setDepartment(Department department) {
		this.department = department;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email + ", gender=" + gender + ", department=" + department
				+ "]";
	}
	public Employee(Integer id, String lastName, String email, Integer gender,
			Department department) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.department = department;
	}
	public Employee() {
		// TODO Auto-generated constructor stub
	}
}

addemp.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>添加员工页面</title>
</head>
<body>
    <form th:action="@{/emps}" method="post">
        员工姓名:<input type="text" name="lastName"><br>
        员工邮箱:<input type="text" name="email"><br>
        员工性别:<input type="radio" name="gender" value="1"><input type="radio" name="gender" value="0"><br>
        员工部门:<select name="department.id">
                    <option th:each="dept:${depts}"
                        th:value="${dept.id}"
                        th:text="${dept.departmentName}"
                    ></option>
                </select><br>
        <input type="submit" value="添加员工">
    </form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是首页</h1>
    <a th:href="@{/emps}">获取所有员工信息</a>
</body>
</html>

list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:align="center">
        <table th:border="1" th:width="550px" th:height="350px" >
            <tr>
                <th>Id</th>
                <th>LastName</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Department</th>
                <th colspan="2">Operate</th>
            </tr>
            <tr th:each="emp:${emps}" th:align="center">
                <td th:text="${emp.id}"></td>
                <td th:text="${emp.lastName}"></td>
                <td th:text="${emp.email}"></td>
                <td th:text="${emp.gender==1?'':''}"></td>
                <td th:text="${emp.department.departmentName}"></td>
                <td>
                    <a th:href="@{/toUpdatPage/}+${emp.id}">EDIT|</a>
                    <!-- <a th:href="@{/}">DETELE</a>-->
                    <form id="myForm" th:action="@{/emps/}+${emp.id}" method="post">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="submit" value="DETELE">
                    </form>
                </td>
            </tr>
        </table>
        <a th:href="@{/toAddPage}" >添加员工</a>
    </div>

</body>
</html>

updateemp.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>修改员工信息</title>
</head>
<body>
<form th:action="@{/emps}" method="post">
    <input type="hidden" name="_method" value="put">
    员工ID:<input type="text" name="id" th:value="${emp.id}" readonly><br>
    员工姓名:<input type="text" name="lastName" th:value="${emp.lastName}"><br>
    员工邮箱:<input type="text" name="email" th:value="${emp.email}"><br>
    员工性别:<input type="radio" name="gender" value="1" th:checked="${emp.gender==1}"><input type="radio" name="gender" value="0" th:checked="${emp.gender==0}"><br>
    员工部门:<select name="department.id">
    <option th:each="dept:${depts}"
            th:value="${dept.id}"
            th:text="${dept.departmentName}"
            th:selected="${emp.department.id==dept.id}"
    ></option>
</select><br>
    <input type="submit" value="修改员工">
</form>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值