• 使用Restful风格实现crud


    使用了springmvc ajax  jquey实现

     

    7.1.0首页

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>欢迎</title>
    </head>
    <body>
        <a href="emps">员工信息</a>
    </body>
    </html>

     

    7.1.1 显示所有员工信息

    1)    URI:emps

    2)    请求方式:GET

    Controller层

        /**
         * 获取所有员工的信息
         * 
         */
        @RequestMapping("/emps")
        public String getAll(Map<String,Object> map) {
            Collection<Employee> emps = employeeDao.getAll();
            //将所有员工信息存入request域
            map.put("emps", emps);
            return "list";
        }

    list.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>展示员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_like.css" />
    <script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        //预加载函数(文档就绪函数)
        // $(this)表示当前触发事件的元素,即为这个超链接
        // $(this).attr("href")  == this.href
        $(function(){
            $(".del").click(function(){
                if(confirm("确认删除吗?")){
                    //submit()将所获取的表单提交
                    $("form").attr("action",$(this).attr("href")).submit()
                    return false;//将超链接的默认行为取消
                }
                return false;
            });
            
        });
    </script>
    </head>
    <body>
    
        <table>
            <tr>
                <th>ID</th>
                <th>LASTNAME</th>
                <th>EMAIL</th>
                <th>GENDER</th>
                <th>DEPARTMENTNAME</th>
                <th>OPTION(<a href="emp">ADD</a>)</th>
            </tr>
            <c:forEach items="${emps }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.lastName }</td>
                    <td>${emp.email }</td>
                    <td>${emp.gender==0?'女':'男' }</td>
                    <td>${emp.department.departmentName }</td>
                    <td>
                        <a href="emp/${emp.id }">UPDATE</a>
                        <a class="del"  href="${pageContext.servletContext.contextPath }/emp/${emp.id }">DELETE</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
        
        <form  method ="post">
            <input type="hidden" name="_method" value="delete" />
        </form>
    
    </body>
    </html>

    7.1.2 添加操作-去往添加页面

    1)  显示添加页面:

    2)  URI:emp

    3)  请求方式:GET

    Controller层

    /**
         * 跳转到添加页面
         */
        @RequestMapping(value="/emp" ,method=RequestMethod.GET)
        public String toAdd(Map<String,Object> map) {
            Collection<Department> depts = departmentDao.getDepartments();
            //将所有部门信息存入ruquest域
            map.put("depts", depts);
            return "add";
        }

    add.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>添加员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
    </head>
    <body>
        
        <form action="emp" method="post">
            <table>
                <tr>
                    <th colspan="2">添加员工信息</th>
                </tr>
                <tr>
                    <td>LASTNAME</td>
                    <td>
                        <input type="text" name="lastName" />
                    </td>
                </tr>
                <tr>
                    <td>EMAIL</td>
                    <td>
                        <input type="text" name="email" />
                    </td>
                </tr>
                <tr>
                    <td>GENDER</td>
                    <td>
                        <input type="radio" name="gender" value="1" /><input type="radio" name="gender" value="0" /></td>
                </tr>
                <tr>
                    <td>DEPARTMENT</td>
                    <td>
                        <select name="department.id">
                            <option>-SELECT DEPARTMENT-</option>
                            <c:forEach items="${depts }" var="dept">
                                <option value="${dept.id }">${dept.departmentName }</option>
                            </c:forEach>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="ADD" />
                    </td>
                </tr>
            </table>
        </form>
    
    </body>
    </html>

    7.1.3 添加操作-添加员工

    1)  添加员工信息:

    2)  URI:emp

    3)  请求方式:POST

    4)  显示效果:完成添加,重定向到 list 页面。

    Controller层

        /**
         * 添加员工信息
         * ** 一般增删改都是需要重定向回查询所有页面,转发操作容易造成表单重复提交问题
         * @param employee
         * @return
         */
        @RequestMapping(value="/emp", method=RequestMethod.POST)
        public String addEmp(Employee employee) {
            employeeDao.save(employee);
            return "redirect:/emps";
        }

    list.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>展示员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_like.css" />
    <script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        //预加载函数(文档就绪函数)
        // $(this)表示当前触发事件的元素,即为这个超链接
        // $(this).attr("href")  == this.href
        $(function(){
            $(".del").click(function(){
                if(confirm("确认删除吗?")){
                    //submit()将所获取的表单提交
                    $("form").attr("action",$(this).attr("href")).submit()
                    return false;//将超链接的默认行为取消
                }
                return false;
            });
            
        });
    </script>
    </head>
    <body>
    
        <table>
            <tr>
                <th>ID</th>
                <th>LASTNAME</th>
                <th>EMAIL</th>
                <th>GENDER</th>
                <th>DEPARTMENTNAME</th>
                <th>OPTION(<a href="emp">ADD</a>)</th>
            </tr>
            <c:forEach items="${emps }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.lastName }</td>
                    <td>${emp.email }</td>
                    <td>${emp.gender==0?'女':'男' }</td>
                    <td>${emp.department.departmentName }</td>
                    <td>
                        <a href="emp/${emp.id }">UPDATE</a>
                        <a class="del"  href="${pageContext.servletContext.contextPath }/emp/${emp.id }">DELETE</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
        
        <form  method ="post">
            <input type="hidden" name="_method" value="delete" />
        </form>
    
    </body>
    </html>

    7.1.4 修改操作-去往修改页面

    1)    URI:emp/{id}

    2)    请求方式:GET

    3)    显示效果:回显表单

    Controller层

        /**
         * 获取回显数据
         * 跳转到修改页面并回显
         */
        @RequestMapping(value="/emp/{id}" ,method=RequestMethod.GET)
        public String toUpdate(@PathVariable("id")Integer id,Map<String,Object> map) {
            //获取要修改的员工信息(即指定的一条数据)
            Employee emp = employeeDao.get(id);
            //把数据放到request域中
            map.put("emp", emp);
            //提供所有的部门信息供员工选择
            Collection<Department> depts = departmentDao.getDepartments();
            map.put("depts", depts);
            return "update";
        }

    update.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>修改员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_like.css"/>
    </head>
    <body>
    
    <!-- 可以将table写在form表单中,因为form是块级元素 -->
        <form action="${pageContext.servletContext.contextPath }/emp" method="post">
            <input type = "hidden" name="id" value="${emp.id }"/>
            <input type = "hidden" name="_method" value="put">
    <table> <tr> <th colspan="2">修改员工信息</th> </tr> <tr> <td>LASTNAME</td> <td> <input type="text" name="lastName" value="${emp.lastName }"/> </td> </tr> <tr> <td>EMAIL</td> <td> <input type="text" name="email" value="${emp.email }"/> </td> </tr> <tr> <td>GENDER</td> <td> <input type="radio" name="gender" value="1" ${emp.gender==1?'checked':'' }/><input type="radio" name="gender" value="0" ${emp.gender==0?'checked':'' }/></td> </tr> <tr> <td>DEPARTMENT</td> <td> <select name="department.id"> <option>--SELECT DEPARTMENT--</option> <c:forEach items="${depts }" var="dept"> <option value="${dept.id }" ${dept.id==emp.department.id?'selected':'' }>${dept.departmentName }</option> </c:forEach> </select> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="update"/> </td> </tr> </table> </form> </body> </html>

     7.1.5 修改操作-修改员工

    1)    URI:emp

    2)    请求方式:PUT

    3)    显示效果:完成修改,重定向到 list 页面。

    Controller层

        /**
         * 修改员工信息
         */
        @RequestMapping(value="/emp", method=RequestMethod.PUT)
        public String updateEmpl(Employee employee) {
            employeeDao.save(employee);//修改
            return "redirect:/emps";
        }

    list.jsp

     7.1.6    删除操作

    1)    URL:emp/{id}

    2)    请求方式:DELETE

    3)    删除后效果:对应记录从数据表中删除

    list.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>展示员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_like.css" />
    <script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        //预加载函数(文档就绪函数)
        // $(this)表示当前触发事件的元素,即为这个超链接
        // $(this).attr("href")  == this.href
        $(function(){
            $(".del").click(function(){
                if(confirm("确认删除吗?")){
                    //submit()将所获取的表单提交
                    $("form").attr("action",$(this).attr("href")).submit()
                    return false;//将超链接的默认行为取消
                }
                return false;
            });
               });
    </script>
    </head>
    <body>
    
        <table>
            <tr>
                <th>ID</th>
                <th>LASTNAME</th>
                <th>EMAIL</th>
                <th>GENDER</th>
                <th>DEPARTMENTNAME</th>
                <th>OPTION(<a href="emp">ADD</a>)</th>
            </tr>
            <c:forEach items="${emps }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.lastName }</td>
                    <td>${emp.email }</td>
                    <td>${emp.gender==0?'女':'男' }</td>
                    <td>${emp.department.departmentName }</td>
                    <td>
                        <a href="emp/${emp.id }">UPDATE</a>
                        <a class="del"  href="${pageContext.servletContext.contextPath }/emp/${emp.id }">DELETE</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
        
        <form  method ="post">
            <input type="hidden" name="_method" value="delete" />
        </form>
    
    </body>
    </html>

    Controller层

        /**
         * 删除员工信息
         */
        @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
        public String deleteEmpl(@PathVariable("id")Integer id) {
            employeeDao.delete(id);
            return "redirect:/emps";
        }

     7.1.7 相关的类

       省略了Service层,为了演示

    1)    实体类:Employee、Department

    Employee类

    package com.atguigu.rest.crud.bean;
    
    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
        }
    }

    Department类

    package com.atguigu.rest.crud.bean;
    
    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
                    + "]";
        }
        
    }

    2)    Controller层:EmplController

    package com.atguigu.rest.crud.controller;
    
    import java.util.Collection;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.atguigu.rest.crud.bean.Department;
    import com.atguigu.rest.crud.bean.Employee;
    import com.atguigu.rest.crud.dao.DepartmentDao;
    import com.atguigu.rest.crud.dao.EmployeeDao;
    @Controller
    public class EmplController {
        @Autowired
        private EmployeeDao employeeDao;
        @Autowired
        private DepartmentDao departmentDao;
        
        /**
         * 获取所有员工的信息
         * 
         */
        @RequestMapping("/emps")
        public String getAll(Map<String,Object> map) {
            Collection<Employee> emps = employeeDao.getAll();
            //将所有员工信息存入request域
            map.put("emps", emps);
            return "list";
        }
        
        
        /**
         * 跳转到添加页面
         */
        @RequestMapping(value="/emp" ,method=RequestMethod.GET)
        public String toAdd(Map<String,Object> map) {
            Collection<Department> depts = departmentDao.getDepartments();
            //将所有部门信息存入ruquest域
            map.put("depts", depts);
            return "add";
        }
        
        /**
         * 添加员工信息
         * ** 一般增删改都是需要重定向回查询所有页面,转发操作容易造成表单重复提交问题
         * @param employee
         * @return
         */
        @RequestMapping(value="/emp", method=RequestMethod.POST)
        public String addEmp(Employee employee) {
            employeeDao.save(employee);
            return "redirect:/emps";
        }
        
        
        
        
        
        
        /**
         * 获取回显数据
         * 跳转到修改页面并回显
         */
        @RequestMapping(value="/emp/{id}" ,method=RequestMethod.GET)
        public String toUpdate(@PathVariable("id")Integer id,Map<String,Object> map) {
            //获取要修改的员工信息(即指定的一条数据)
            Employee empl = employeeDao.get(id);
            //把数据放到request域中
            map.put("empl", empl);
            //提供所有的部门信息供员工选择
            Collection<Department> depts = departmentDao.getDepartments();
            map.put("depts", depts);
            return "update";
        }
        
        /**
         * 修改员工信息
         */
        @RequestMapping(value="/emp", method=RequestMethod.PUT)
        public String updateEmpl(Employee employee) {
            employeeDao.save(employee);//修改
            return "redirect:/emps";
        }
        
        
        
        /**
         * 删除员工信息
         */
        @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
        public String deleteEmpl(@PathVariable("id")Integer id) {
            employeeDao.delete(id);
            return "redirect:/emps";
        }
    
    }

    3)    Dao:EmployeeDao、DepartmentDao

    EmployeeDao

        package com.atguigu.rest.crud.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.atguigu.rest.crud.bean.Department;
    import com.atguigu.rest.crud.bean.Employee;
    
    @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()));
            //若key有值则实现覆盖,修改操作
            //若key无值则实现增加,添加操作
            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);
        }
    }

    DepartmentDao

    package com.atguigu.rest.crud.dao;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.stereotype.Repository;
    
    import com.atguigu.rest.crud.bean.Department;
    
    
    @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);
        }
        
    }

           7.1.8 相关的页面

    1)    list.jsp

    2)    add.jsp

    3)    upload.jsp

    4)    edit.jsp

    5)   index.jsp


    7.2 搭建开发环境

    1)    拷贝jar包

    commons-logging-1.1.3.jar

    spring-beans-4.0.0.RELEASE.jar

    spring-context-4.0.0.RELEASE.jar

    spring-core-4.0.0.RELEASE.jar

    spring-expression-4.0.0.RELEASE.jar

    spring-web-4.0.0.RELEASE.jar

    spring-webmvc-4.0.0.RELEASE.jar

    2)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">
      <display-name>RestEmpl</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <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>
      </filter>
      <filter-mapping>
          <filter-name>CharacterEncodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>
      
        <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>
      
      <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>

    3)    创建配置文件:springmvc.xml  增加context,mvc,beans名称空间。

    <?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">
        
        <!-- 开启扫描 -->
        <context:component-scan base-package="com.atguigu.rest.crud"></context:component-scan>
        
        <!-- 配置视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/view/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        
        <!-- 
            配置tomcat中默认的servlet,DefaultServlet
            注意:当DefaultServlet所设置的<url-patter>的值与开发人员配置的servlet的<url-patter>相同
            以开发人员所配置的优先
            作用:当客户端发送请求,由于defaultServlet所设置的<url-patter> 开发人员所设置的<url-patter> 都是/
            因此先通过DefaultServlet处理请求,找该请求是否有相应的处理器,有则处理,无则交给defaultServlet处理
            
         -->
        <mvc:default-servlet-handler/>
        <!--  mvc驱动-->
        <mvc:annotation-driven />
    
    </beans>

    三、使用<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>重构restful

    3.1edit.jsp(添加、修改功能集于一身)

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
    <!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>编辑员工信息</title>
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
    </head>
    <body>
        <!-- modelAttribute自定义回显对象的属性名 -->
        <form:form action="${pageContext.servletContext.contextPath }/emp" method="post" modelAttribute="emp">
            
            <c:if test="${empty emp.id }" var="flag"></c:if>
            <c:if test="${!flag }">
                <form:hidden path="id"/>
                <input type="hidden" name="_method" value="PUT" />
            </c:if>
            
            <table>
                <tr>
                    <th colspan="2">
                        <c:if test="${flag }">添加员工信息</c:if>
                        <c:if test="${!flag }">修改员工信息</c:if>
                    </th>
                </tr>
                <tr>
                    <td>LASTNAME</td>
                    <td>
                        <form:input path="lastName"/>
                    </td>
                </tr>
                <tr>
                    <td>EMAIL</td>
                    <td>
                        <form:input path="email"/>
                    </td>
                </tr>
                <tr>
                    <td>GENDER</td>
                    <td>
                        <form:radiobuttons path="gender" items="${genders }"/>
                以下黄颜色标识实现的功能与以上黄颜色实现功能一致

                <input type="radio" name="gender" value="1" ${empl.gender==1?'checked':'' }/>男
                  <input type="radio" name="gender" value="0" ${empl.gender==0?'checked':'' }/>女 </td> </tr> <tr> <td>DEPARTMENT</td> <td> <form:select path="department.id" items="${depts }" itemLabel="departmentName" itemValue="id"></form:select>
                  以下黄颜色标识实现的功能与以上黄颜色实现功能一致
                <select name="department.id">
                    <option>--SELECT DEPARTMENT--</option>
                    <c:forEach items="${depts }" var="dept">
                     <option value="${dept.id }" ${dept.id==empl.department.id?'selected':'' }>${dept.departmentName }</option>
                    </c:forEach>
                  </select> </td> </tr> <tr> <td colspan="2"> <c:if test="${flag }"> <input type="submit" value="ADD" /> </c:if> <c:if test="${!flag }"> <input type="submit" value="UPDATE" /> </c:if> </td> </tr> </table> </form:form> </body> </html>

    3.2EmpController

    package com.atguigu.rest.crud.controller;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.atguigu.rest.crud.bean.Department;
    import com.atguigu.rest.crud.bean.Employee;
    import com.atguigu.rest.crud.dao.DepartmentDao;
    import com.atguigu.rest.crud.dao.EmployeeDao;
    
    //@Controller
    public class EmpController_ {
    
        @Autowired
        private EmployeeDao employeeDao;
        
        @Autowired
        private DepartmentDao departmentDao;
        
        /**
         * 获取所有的员工信息
         * @param map
         * @return
         */
        @RequestMapping(value="/emps")
        public String getAll(Map<String, Object> map) {
            Collection<Employee> emps = employeeDao.getAll();
            map.put("emps", emps);
            return "list";
        }
        
        /**
         * 跳转到添加页面
         * @return
         */
        @RequestMapping(value="/emp", method=RequestMethod.GET)
        public String toAdd(Map<String, Object> map) {
            //获取所有的部门信息
            Collection<Department> depts = departmentDao.getDepartments();
            //创建存储性别gender的信息
            Map<String, String> genders = new HashMap<>();
            genders.put("0", "女");
            genders.put("1", "男");
            map.put("depts", depts);
            map.put("genders", genders);
            //form标签有自动回显的功能,会在页面中能够默认获取request作用于中command属性的值
            //map.put("command", new Employee());
            //若在<form:form>设置了modelAttribute,就可以自定义回显对象的属性名
            map.put("emp", new Employee());
            return "edit";
        }
        
        /**
         * 添加员工信息
         * @param employee
         * @return
         */
        @RequestMapping(value="/emp", method=RequestMethod.POST)
        public String addEmp(Employee employee) {
            employeeDao.save(employee);
            return "redirect:/emps";
        }
        
        /**
         * 获取要回显的数据,跳转到修改页面,并回显
         * @param id
         * @param map
         * @return
         */
        @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
        public String toUpdate(@PathVariable("id") Integer id, Map<String, Object> map) {
            //获取要修改的员工信息
            Employee emp = employeeDao.get(id);
            //所有的部门信息,供用户选择
            Collection<Department> depts = departmentDao.getDepartments();
            //设置存储性别的map集合
            Map<String, String> genders = new HashMap<>();
            genders.put("0", "女");
            genders.put("1", "男");
            map.put("emp", emp);
            map.put("depts", depts);
            map.put("genders", genders);
            return "edit";
        }
        
        @RequestMapping(value="/emp", method=RequestMethod.PUT)
        public String updateEmp(Employee employee) {
            employeeDao.save(employee);//修改
            return "redirect:/emps";
        }
        
    }
  • 相关阅读:
    List的Select 和Select().tolist()
    lambda中FirstOrDefault和First
    EF时,数据库字段和实体类不一致问题
    用户变量问题
    实验十二:字符串和结构
    实验十一:指针(2)
    实验十:指针(1)
    实验九:二维数组和字符数组的应用
    实验八:一维数组的应用
    实验七:函数及数组(1)
  • 原文地址:https://www.cnblogs.com/lsk-130602/p/12238911.html
Copyright © 2020-2023  润新知