SpringMVC-7 RESTful CRUD

本文介绍了一个基于Spring MVC的RESTful风格CRUD操作实例,详细展示了Department和Employee两个实体类的增删改查功能实现过程。

  RESTful风格CRUD操作的具体实现代码下载地址:http://download.youkuaiyun.com/download/bingbeichen/9795651


1. 具体需求

  这里写图片描述


2. 代码结构

  这里写图片描述


3. 具体实现

  DepartmentDao.java:

package com.qiaobc.springmvc.dao;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.qiaobc.springmvc.domain.Department;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> depts = null;

    static {
        depts = new LinkedHashMap<Integer, Department>();

        depts.put(101, new Department(101, "dept-101"));
        depts.put(102, new Department(102, "dept-102"));
        depts.put(103, new Department(103, "dept-103"));
    }

    public Collection<Department> getDepartments(){
        return depts.values();
    }

    public Department getDepartment(Integer deptId) {
        return depts.get(deptId);
    }

}

  EmployeeDao.java:

package com.qiaobc.springmvc.dao;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.qiaobc.springmvc.domain.Department;
import com.qiaobc.springmvc.domain.Employee;

@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> emps = null;

    static {
        emps = new LinkedHashMap<Integer, Employee>();

        emps.put(1001, new Employee(1001, "qiaobc1001", "qiaobc1001@163.com", "1", new Department(101, "dept-101")));
        emps.put(1002, new Employee(1002, "qiaobc1002", "qiaobc1002@163.com", "0", new Department(102, "dept-102")));
        emps.put(1003, new Employee(1003, "qiaobc1003", "qiaobc1003@163.com", "1", new Department(103, "dept-103")));
        emps.put(1004, new Employee(1004, "qiaobc1004", "qiaobc1004@163.com", "0", new Department(102, "dept-102")));
        emps.put(1005, new Employee(1005, "qiaobc1005", "qiaobc1005@163.com", "1", new Department(101, "dept-101")));
    }

    public Collection<Employee> getEmployees() {
        return emps.values();
    }

    private static Integer initId = 1006;

    @Autowired
    private DepartmentDao departmentDao;

    public void save(Employee employee) {
        if(employee.getId() == null) {
            employee.setId(initId++);
        }

        employee.setDept(departmentDao.getDepartment(employee.getDept().getDeptId()));
        emps.put(employee.getId(), employee);
    }

    public void delete(Integer id) {
        emps.remove(id);
    }

    public Employee get(Integer id) {
        return emps.get(id);
    }

}

  Department.java:

package com.qiaobc.springmvc.domain;

public class Department {

    private Integer deptId;

    private String deptName;

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public Department(Integer deptId, String deptName) {
        super();
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public Department() {
        super();
    }

    @Override
    public String toString() {
        return "Department [deptId=" + deptId + ", deptName=" + deptName + "]";
    }

}

  Employee.java:

package com.qiaobc.springmvc.domain;

public class Employee {

    private Integer id;

    private String name;

    private String email;

    private String gender;

    private Department dept;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    public Employee(Integer id, String name, String email, String gender,
            Department dept) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.gender = gender;
        this.dept = dept;
    }

    public Employee() {
        super();
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", email=" + email
                + ", gender=" + gender + ", dept=" + dept + "]";
    }

}

  EmployeeHandler.java:

package com.qiaobc.springmvc.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.qiaobc.springmvc.dao.DepartmentDao;
import com.qiaobc.springmvc.dao.EmployeeDao;
import com.qiaobc.springmvc.domain.Employee;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping(value="/emps", method=RequestMethod.GET)
    public String list(Map<String, Object> map) {
        map.put("employees", employeeDao.getEmployees());
        return "emp-list";
    }

    @RequestMapping(value="/emp", method=RequestMethod.GET)
    public String input(Map<String, Object> map) {
        map.put("employee", new Employee());
        map.put("departments", departmentDao.getDepartments());
        return "emp-edit";
    }

    @RequestMapping(value="/emp", method=RequestMethod.POST)
    public String save(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
    public String input(Map<String, Object> map, @PathVariable(value="id") Integer id) {
        map.put("employee", employeeDao.get(id));
        map.put("departments", departmentDao.getDepartments());
        return "emp-edit";
    }

    @ModelAttribute
    public void getEmployee(@RequestParam(value="id", required=false) Integer id, Map<String, Object> map) {
        if(id != null) {
            map.put("employee", employeeDao.get(id));
        }
    }

    @RequestMapping(value="/emp", method=RequestMethod.PUT)
    public String update(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

}

  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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.qiaobc.springmvc"></context:component-scan>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

  emp-edit.jsp:

<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <!-- 
        SpringMVC的form标签可以更快速地开发表单页面,并实现表单的回显
        注意:
            可以通过modelAttribute属性指定所绑定的模型属性
            若未指定该属性,则默认从request域对象中获取名为command的表单Bean对象,若不存在则报错!
     -->
    <form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee">
        <!-- path属性对应HTML表单标签的name属性值 -->
        <c:if test="${!empty id }">
            <form:hidden path="id"/>
            <input type="hidden" name="_method" value="PUT">
            Name:<form:input path="name" disabled="true"/>
        </c:if>
        <c:if test="${empty id }">
            Name:<form:input path="name"/>
        </c:if>
        <br><br>

        Email:<form:input path="email"/><br><br>
        <%
            Map<String, String> genders = new HashMap<String, String>();
            genders.put("1", "Male");
            genders.put("0", "Female");
            request.setAttribute("genders", genders);
        %>
        Gender:<form:radiobuttons path="gender" items="${genders }"/><br><br>
        Department:<form:select path="dept.deptId" items="${departments }" 
            itemLabel="deptName" itemValue="deptId" ></form:select><br><br>
        <input type="submit" name="submit">
    </form:form>

</body>
</html>

  emp-list.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<!-- 
    关于SpringMVC处理静态资源的问题:
        1). DispatcherServlet的请求映射配置为“/”,即SpringMVC将捕获WEB容器的所有请求
        2). 静态资源的请求如scripts/jquery-1.7.2.js会被捕获,会因找不到对应处理器将导致错误
        3). 而优雅的REST风格的资源URL不希望带.do等后缀,即不能使用“/*.do”
    解决办法:
        1). 在SpringMVC配置文件中,配置<mvc:default-servlet-handler/>
        2). 且需要配置<mvc:annotation-driven></mvc:annotation-driven>
 -->
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function() {
        $(".delete").click(function(){
            var href = $(this).attr("href");
            $("form").attr("action", href).submit();
            return false;
        });
    });
</script>

<body>

    <form action="" method="post">
        <input type="hidden" name="_method" value="DELETE">
    </form>

    <c:if test="${empty requestScope.employees }">
        对不起,暂没有员工信息!
    </c:if>
    <c:if test="${!empty requestScope.employees }">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>EMAIL</th>
                <th>GENDER</th>
                <th>DEPARTMENT</th>
                <th>DELETE</th>
                <th>EDIT</th>
            </tr>
            <c:forEach items="${requestScope.employees }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.name }</td>
                    <td>${emp.email }</td>
                    <td>${emp.gender == "1" ? "Female" : "Male" }</td>
                    <td>${emp.dept.deptName }</td>
                    <td><a href="emp/${emp.id }" class="delete">Delete</a></td>
                    <td><a href="emp/${emp.id }">Edit</a></td>
                </tr>
            </c:forEach>
        </table>
    </c:if>

</body>
</html>

  web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <!-- 配置SpringMVC所需要的DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置HiddenHttpMethodFilter:将POST请求转换为DELETE或PUT请求 -->
    <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>

</web-app>

  index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <!-- 显示所有员工信息的请求:HTTP GET -->
    <a href="emps">List All Employees!</a>
    <br><br>

    <!-- 添加新的员工信息的请求:HTTP GET -->
    <a href="emp">Add New Employee!</a>
    <br><br>

</body>
</html>
代码转载自:https://pan.quark.cn/s/7f503284aed9 Hibernate的核心组件总数达到五个,具体包括:Session、SessionFactory、Transaction、Query以及Configuration。 这五个核心组件在各类开发项目中都具有普遍的应用性。 借助这些组件,不仅可以高效地进行持久化对象的读取与存储,还能够实现事务管理功能。 接下来将通过图形化的方式,逐一阐述这五个核心组件的具体细节。 依据所提供的文件内容,可以总结出以下几个关键知识点:### 1. SSH框架详细架构图尽管标题提及“SSH框架详细架构图”,但在描述部分并未直接呈现关于SSH的详细内容,而是转向介绍了Hibernate的核心接口。 然而,在此我们可以简要概述SSH框架(涵盖Spring、Struts、Hibernate)的核心理念及其在Java开发中的具体作用。 #### Spring框架- **定义**:Spring框架是一个开源架构,其设计目标在于简化企业级应用的开发流程。 - **特点**: - **分层结构**:该框架允许开发者根据实际需求选择性地采纳部分组件,而非强制使用全部功能。 - **可复用性**:Spring框架支持创建可在不同开发环境中重复利用的业务逻辑和数据访问组件。 - **核心构成**: - **核心容器**:该部分包含了Spring框架的基础功能,其核心在于`BeanFactory`,该组件通过工厂模式运作,并借助控制反转(IoC)理念,将配置和依赖管理与具体的应用代码进行有效分离。 - **Spring上下文**:提供一个配置文件,其中整合了诸如JNDI、EJB、邮件服务、国际化支持等企业级服务。 - **Spring AO...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值