美文网首页
springmvc 08 restful crud

springmvc 08 restful crud

作者: 小小机器人 | 来源:发表于2016-10-24 09:43 被阅读39次

项目结构

jar包

配置文件

<?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/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.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.xxjqr"></context:component-scan>
    
    <!-- 配置视图转发器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 处理静态资源请求 -->
    <mvc:default-servlet-handler />
    
    <!-- 使用了上面的标签后还是需要使用该标签来开启非静态资源请求的拦截 -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

前端页面

//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>
    <a href="list">show all employees</a>
</body>
</html>
//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>
<!-- 静态资源请求的问题
http://www.cnblogs.com/fangqi/archive/2012/10/28/2743108.html
 -->
<script type="text/javascript" src="scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript"> 
    $(function(){
        $(".delete").click(function(){
            var href = $(this).attr("href");
            $("form").attr("action", href).submit();            
            return false;
        });
    })
</script>
</head>
<body>
    
    <!-- 该form是用来给delete操作做占位用的 -->
    <form action="" method="post">
        <input type="hidden" name="_method" value="DELETE"/>
    </form>

    <c:if test="${empty requestScope.emps}">
        目前没有任何员工信息
    </c:if>
    
    <c:if test="${!empty requestScope.emps}">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Department</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            
            
            <c:forEach items="${requestScope.emps}" var="emp">
                <tr>
                    <td>${emp.empId}</td>
                    <td>${emp.empName}</td>
                    <td>${emp.empEmail}</td>
                    <td>${emp.empGender==0?'Female':'Male'}</td>
                    <td>${emp.department.deptName}</td>
                    <td><a href="emp/${emp.empId}">Edit</a></td>
                    <td><a class="delete" href="emp/${emp.empId}">Delete</a></td>
                </tr>
            </c:forEach>

        </table>
    </c:if>
    
    <br>
    <a href="emp">Add employee</a>

</body>
</html>
//input.jsp
<%@ 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>
    <form:form action="${pageContext.request.contextPath}/emp" method="post" modelAttribute="employee">
        <c:if test="${!empty employee.empId}">
            <form:hidden path="empId"/><!-- id要设成隐藏域注入javabean,否则javabean的id属性为Null -->
            <input type="hidden" name="_method" value="PUT"/>
        </c:if>
        
        name:<form:input path="empName"/><br>
        email:<form:input path="empEmail"/><br>
        
        gender:
        <form:radiobuttons path="empGender" items="${genders}"/><br>
        <!-- items是显示的数据源(map类型)
        提交表单后注入的是map的key值 -->
        
       department:
       <form:select path="department.deptId" items="${depts}" itemLabel="deptName" itemValue="deptId"></form:select>
        <!--
            因为提交表单时不能直接返回一个对象类型,那么这里我们不能直接注入employee的department属性
            所以我们可以用级联特性注入department属性的id属性值
            
            itemLabel:列表显示出来的内容 (deptName是Map中对象类型中的属性)
            itemValue:列表显示内容选中后对应的value值 (deptName也是Map中对象类型中的属性);
            
            注意:要使用itemLabel,itemValue属性,那么数据源必须是Collection或Array类型
        -->
        <br><button type="submit">提交</button>
    </form:form>
    
    <!-- spring form标签
    form标签默认需要绑定一个javabean对象,默认bean名称是"command"
    通常我们都会指定commandName或modelAttribute 属性,来指定使用绑定到的JavaBean的名称
    
    绑定的javabean对象是必须存在于model中的哦,这里绑定的javabean名称是model中的attibuteName
     -->
</body>
</html>

handlers包

@Controller
public class EmployeeHandler {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    
    @RequestMapping(value="/list")
    public String list(Map<String,Object> map){
        map.put("emps",employeeDao.getAll());
        return "list";
    }
    
    
    //点击Add employee 链接会进来
    @RequestMapping(value={"/emp"},method=RequestMethod.GET)
    public String input(Map<String,Object> map){
        //springmvc表单标签 性别单选选项数据源
        Map<Integer,String> genders = new HashMap<Integer,String>();
        genders.put(0, "Female");
        genders.put(1, "Male");
        
        map.put("genders", genders);
        map.put("employee",new Employee());//springmvc的表单标签 对应bean
        map.put("depts", departmentDao.getAll());//springmvc表单标签 部门数据源
        
        return "input";
    }
    
    /**添加Employee*/
    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String save(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:list";
    }
    
    /**删除指定id的Employee*/
    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/list";
    }
    
    /*点击Edit会进来*/
    @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
    public String input(
            @PathVariable("id") Integer id
            ,Map<String,Object> map){
        //springmvc表单标签 性别单选选项数据源
        Map<Integer,String> genders = new HashMap<Integer,String>();
        genders.put(0, "Female");
        genders.put(1, "Male");
        
        map.put("genders", genders);
        map.put("depts", departmentDao.getAll());//springmvc表单标签 部门数据源
        map.put("employee",employeeDao.getEmployee(id));//springmvc的表单标签 对应bean
        //model中放入employee bean,前端表单有会有回显
        
        return "input";
    }
    
    /**更新操作*/
    @RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/list";
    }
}

dao包

package com.xxjqr.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.xxjqr.entities.Department;

@Repository
public class DepartmentDao {
    private static Map<Integer,Department> depts;
    static {
        depts = new HashMap<Integer,Department>();
        depts.put(101, new Department(101,"开发部"));
        depts.put(102, new Department(102,"宣传部"));
        depts.put(103, new Department(103,"销售部"));
        depts.put(104, new Department(104,"研发部"));
        depts.put(105, new Department(105,"账务部"));
    }
    
    public Collection<Department> getAll(){
        return depts.values();
    }
    
    public Department getDepartment(Integer id){
        return depts.get(id);
    }
    
}

package com.xxjqr.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

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

import com.xxjqr.entities.Department;
import com.xxjqr.entities.Employee;

@Repository
public class EmployeeDao {
    private static Map<Integer,Employee> emps;
    private static Integer empId = 1006;
    @Autowired
    private DepartmentDao deptDao;
    
    static {
        emps = new HashMap<Integer,Employee>();
        emps.put(1001, new Employee(1001,"Smith","11@qq.com",1,new Department(101,"开发部")));
        emps.put(1002, new Employee(1002,"Johnson","22@qq.com",0,new Department(102,"宣传部")));
        emps.put(1003, new Employee(1003,"Williams","33@qq.com",0,new Department(103,"销售部")));
        emps.put(1004, new Employee(1004,"Brown","44@qq.com",1,new Department(104,"研发部")));
        emps.put(1005, new Employee(1005,"Jones","55@qq.com",0,new Department(105,"账务部")));
    }
    
    public Collection<Employee> getAll(){
        return emps.values();
    }
    
    public void save(Employee employee){
        if (employee.getEmpId() == null){
            employee.setEmpId(empId++);
        }
        employee.setDepartment(deptDao.getDepartment(employee.getDepartment().getDeptId()));
        emps.put(employee.getEmpId(), employee);
    }
    
    public void delete(Integer id){ 
        if(id != null){
            emps.remove(id);
        }
    }
    
    public Employee getEmployee(Integer id){
        if (id !=null)
            return emps.get(id);
        return null;
    }
}

entities包

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private Integer deptId;
    private String deptName;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor
public class Employee {

    private Integer empId;

    @NonNull
    private String empName;
    @NonNull
    private String empEmail;
    @NonNull
    private Integer empGender;//0女,1男
    @NonNull
    private Department department;
}

演示:

相关文章

网友评论

      本文标题:springmvc 08 restful crud

      本文链接:https://www.haomeiwen.com/subject/buucuttx.html