springmvc 08 restful crud

項目結構

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>
    
    <!-- 配置視圖轉發(fā)器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 處理靜態(tài)資源請求 -->
    <mvc:default-servlet-handler />
    
    <!-- 使用了上面的標簽后還是需要使用該標簽來開啟非靜態(tài)資源請求的攔截 -->
    <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>
<!-- 靜態(tài)資源請求的問題
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是顯示的數(shù)據(jù)源(map類型)
        提交表單后注入的是map的key值 -->
        
       department:
       <form:select path="department.deptId" items="${depts}" itemLabel="deptName" itemValue="deptId"></form:select>
        <!--
            因為提交表單時不能直接返回一個對象類型,那么這里我們不能直接注入employee的department屬性
            所以我們可以用級聯(lián)特性注入department屬性的id屬性值
            
            itemLabel:列表顯示出來的內容 (deptName是Map中對象類型中的屬性)
            itemValue:列表顯示內容選中后對應的value值 (deptName也是Map中對象類型中的屬性);
            
            注意:要使用itemLabel,itemValue屬性,那么數(shù)據(jù)源必須是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表單標簽 性別單選選項數(shù)據(jù)源
        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表單標簽 部門數(shù)據(jù)源
        
        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表單標簽 性別單選選項數(shù)據(jù)源
        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表單標簽 部門數(shù)據(jù)源
        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,"開發(fā)部"));
        depts.put(102, new Department(102,"宣傳部"));
        depts.put(103, new Department(103,"銷售部"));
        depts.put(104, new Department(104,"研發(fā)部"));
        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,"開發(fā)部")));
        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,"研發(fā)部")));
        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;
}

演示:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末泳唠,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子宙搬,更是在濱河造成了極大的恐慌笨腥,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勇垛,死亡現(xiàn)場離奇詭異脖母,居然都是意外死亡,警方通過查閱死者的電腦和手機闲孤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門谆级,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人崭放,你說我怎么就攤上這事哨苛。” “怎么了币砂?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵建峭,是天一觀的道長。 經(jīng)常有香客問我决摧,道長亿蒸,這世上最難降的妖魔是什么凑兰? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮边锁,結果婚禮上姑食,老公的妹妹穿的比我還像新娘。我一直安慰自己茅坛,他們只是感情好音半,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贡蓖,像睡著了一般曹鸠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上斥铺,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天彻桃,我揣著相機與錄音,去河邊找鬼晾蜘。 笑死邻眷,一個胖子當著我的面吹牛,可吹牛的內容都是我干的剔交。 我是一名探鬼主播肆饶,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼省容!你這毒婦竟也來了抖拴?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤腥椒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后候衍,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笼蛛,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年蛉鹿,在試婚紗的時候發(fā)現(xiàn)自己被綠了滨砍。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡妖异,死狀恐怖惋戏,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情他膳,我是刑警寧澤响逢,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站棕孙,受9級特大地震影響舔亭,放射性物質發(fā)生泄漏些膨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一钦铺、第九天 我趴在偏房一處隱蔽的房頂上張望订雾。 院中可真熱鬧,春花似錦矛洞、人聲如沸洼哎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽谱净。三九已至,卻和暖如春擅威,著一層夾襖步出監(jiān)牢的瞬間壕探,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工郊丛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留李请,地道東北人。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓厉熟,卻偏偏與公主長得像导盅,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子揍瑟,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,077評論 25 707
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,804評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理白翻,服務發(fā)現(xiàn),斷路器绢片,智...
    卡卡羅2017閱讀 134,652評論 18 139
  • 在這章講的內容是恐懼營銷滤馍,這章的內容真的讓我受益匪淺,之前只知道有情感營銷底循、饑餓營銷巢株、服務營銷、事件營銷等等熙涤。今天...
    可樂1991閱讀 328評論 0 0
  • 不靠譜PsychoPy入門教程目錄: PsychoPy入門00安裝 PsychoPy入門01文字和圖片的呈現(xiàn) Ps...
    ChZ_CC閱讀 6,425評論 2 4