使用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";
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM