国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

Spring Boot 員工管理系統超詳細教程(源碼分享)

發(fā)布時(shí)間:2021-07-06 11:13 來(lái)源:腳本之家 閱讀:0 作者:林深時(shí)不見(jiàn)鹿 欄目: 開(kāi)發(fā)技術(shù)

目錄

        員工管理系統

        1、準備工作

        資料下載

        內含源碼 + 筆記 + web素材

        源碼下載地址:

        筆記

        素材

        源碼

        1.1、導入資源

        將文件夾中的靜態(tài)資源導入idea中

        位置如下

        1.2、編寫(xiě)pojo層

        員工表

        //員工表
        @Data
        @NoArgsConstructor
        public class Employee {
        
            private Integer id;
            private String lastName;
            private String email;
            private Integer gender; //性別 0 女, 1,男
            private Department department;
            private Date birth;
        
            public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
                this.id = id;
                this.lastName = lastName;
                this.email = email;
                this.gender = gender;
                this.department = department;
                this.birth = new Date();
            }
        }

        部門(mén)表

        //部門(mén)表
        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        public class Department {
            private int id;  //部門(mén)id
            private String departmentName;  //部門(mén)名字
        }

        添加lombok依賴(lài)

         <!--lombok-->
                <dependency>
                    <groupId>org.projectlombok</groupId>
                    <artifactId>lombok</artifactId>
                </dependency>

        1.3、編寫(xiě)dao層

        這里我們模擬數據,springboot和數據庫的連接在后序課程中。

        部門(mén)dao

        package com.kuang.dao;
        
        import com.kuang.pojo.Department;
        import org.springframework.stereotype.Repository;
        
        import java.util.Collection;
        import java.util.HashMap;
        import java.util.Map;
        
        //部門(mén)dao
        @Repository
        public class DepartmentDao {
        
            //模擬數據庫中的數據
        
            private static Map<Integer, Department>departments = null;
        
            static {
                departments = new HashMap<Integer, Department>(); //創(chuàng  )建一個(gè)部門(mén)表
        
                departments.put(101,new Department(101,"教學(xué)部"));
                departments.put(102,new Department(102,"市場(chǎng)部"));
                departments.put(103,new Department(103,"教研部"));
                departments.put(104,new Department(104,"運營(yíng)部"));
                departments.put(105,new Department(105,"后勤部"));
            }
        
            //獲取所有的部門(mén)信息
            public Collection<Department> getDepartments(){
                return departments.values();
            }
            //通過(guò)id得到部門(mén)
            public Department getDepartmentById(Integer id){
                return departments.get(id);
            }
        }

        員工dao

        package com.kuang.dao;
        
        import com.kuang.pojo.Department;
        import com.kuang.pojo.Employee;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Repository;
        
        import java.util.Collection;
        import java.util.HashMap;
        import java.util.Map;
        
        //員工dao
        @Repository //被string托管
        public class EmployeeDao {
        
            //模擬數據庫中的數據
            private static Map<Integer, Employee> employees= null;
            //員工所屬的部門(mén)
            @Autowired
            private DepartmentDao departmentDao;
            static {
                employees = new HashMap<Integer,Employee>(); //創(chuàng  )建一個(gè)部門(mén)表
        
                employees.put(1001,new Employee(  1001,"AA","1622840727@qq.com",1,new Department(101,"教學(xué)部")));
                employees.put(1002,new Employee(  1002,"BB","2622840727@qq.com",0,new Department(102,"市場(chǎng)部")));
                employees.put(1003,new Employee(  1003,"CC","4622840727@qq.com",1,new Department(103,"教研部")));
                employees.put(1004,new Employee(  1004,"DD","5628440727@qq.com",0,new Department(104,"運營(yíng)部")));
                employees.put(1005,new Employee(  1005,"FF","6022840727@qq.com",1,new Department(105,"后勤部")));
            }
            //主鍵自增
            private static Integer ininId = 1006;
            //增加一個(gè)員工
            public void save(Employee employee){
                if(employee.getId() == null){
                    employee.setId(ininId++);
                }
                employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
                employees.put(employee.getId(),employee);
            }
            //查詢(xún)全部的員工
            public Collection<Employee>getALL(){
                 return employees.values();
            }
        
            //通過(guò)id查詢(xún)員工
            public Employee getEmployeeById(Integer id){
                return employees.get(id);
            }
        
            //刪除一個(gè)員通過(guò)id
            public void delete(Integer id){
                employees.remove(id);
            }
        }

        2、首頁(yè)實(shí)現

        2.1、引入Thymeleaf

        pom.xml導入依賴(lài)

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

        2.2、編寫(xiě)MyMvcConfig

        package com.kuang.config;
        
        import org.springframework.context.annotation.Configuration;
        import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
        import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
        
        //擴展使用SpringMVC
        @Configuration
        public class MyMvcConfig implements WebMvcConfigurer {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index");
                registry.addViewController("/index.html").setViewName("index");
            }
        }

        更改靜態(tài)資源路徑

        所有的靜態(tài)資源都需要使用thymeleaf接管:@{}

        application.properties 修改

        # 關(guān)閉模板引擎的緩存
        spring.thymeleaf.cache=false
        
        server.servlet.context-path=/kuang

        2.3、測試首頁(yè)

        輸入路徑

        測試成功!

        3、頁(yè)面國際化

        3.1、 File Encodings設置

        先在IDEA中統一設置properties的編碼問(wèn)題!

        編寫(xiě)國際化配置文件,抽取頁(yè)面需要顯示的國際化頁(yè)面消息。我們可以去登錄頁(yè)面查看一下,哪些內容

        我們需要編寫(xiě)國際化的配置!

        3.2、配置文件編寫(xiě)

        1、我們在resources資源文件下新建一個(gè)i18n目錄,存放國際化配置文件

        2、建立一個(gè)login.properties文件,還有一個(gè)login_zh_CN.properties;發(fā)現IDEA自動(dòng)識別了我們要做國際化操作;文件夾變了!

        3、我們可以在這上面去新建一個(gè)文件;

        彈出如下頁(yè)面:我們再添加一個(gè)英文的;

        這樣就快捷多了!

        4、接下來(lái),我們就來(lái)編寫(xiě)配置,我們可以看到idea下面有另外一個(gè)視圖;

        這個(gè)視圖我們點(diǎn)擊 + 號就可以直接添加屬性了;我們新建一個(gè)login.tip,可以看到邊上有三個(gè)文件框可以輸入

        在這里插入圖片描述

        我們添加一下首頁(yè)的內容!

        然后依次添加其他頁(yè)面內容即可!

        然后去查看我們的配置文件;

        login.properties :默認

        login.btn=登錄
        login.password=密碼
        login.remember=記住我
        login.tip=請登錄
        login.username=用戶(hù)名

        英文:

        login.btn=Sign in
        login.password=Password
        login.remember=Remember me
        login.tip=Please sign in
        login.username=Username

        中文:

        login.btn=登錄
        login.password=密碼
        login.remember=記住我
        login.tip=請登錄
        login.username=用戶(hù)名

        OK,配置文件步驟搞定!

        配置文件生效探究

        我們去看一下SpringBoot對國際化的自動(dòng)配置!這里又涉及到一個(gè)類(lèi):MessageSourceAutoConfiguration

        里面有一個(gè)方法,這里發(fā)現SpringBoot已經(jīng)自動(dòng)配置好了管理我們國際化資源文件的組件 ResourceBundleMessageSource;

        // 獲取 properties 傳遞過(guò)來(lái)的值進(jìn)行判斷
        @Bean
        public MessageSource messageSource(MessageSourceProperties properties) {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            if (StringUtils.hasText(properties.getBasename())) {
                // 設置國際化文件的基礎名(去掉語(yǔ)言國家代碼的)
                messageSource.setBasenames(
                    StringUtils.commaDelimitedListToStringArray(
                                               StringUtils.trimAllWhitespace(properties.getBasename())));
            }
            if (properties.getEncoding() != null) {
                messageSource.setDefaultEncoding(properties.getEncoding().name());
            }
            messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
            Duration cacheDuration = properties.getCacheDuration();
            if (cacheDuration != null) {
                messageSource.setCacheMillis(cacheDuration.toMillis());
            }
            messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
            messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
            return messageSource;
        }

        我們真實(shí)的情況是放在了i18n目錄下,所以我們要去配置這個(gè)messages的路徑;

        spring.messages.basename=i18n.login

        配置頁(yè)面國際化值

        去頁(yè)面獲取國際化的值,查看Thymeleaf的文檔,找到message取值操作為:#{…}。我們去頁(yè)面測試下:

        IDEA還有提示,非常智能的!

        我們可以去啟動(dòng)項目,訪(fǎng)問(wèn)一下,發(fā)現已經(jīng)自動(dòng)識別為中文的了!

        但是我們想要更好!可以根據按鈕自動(dòng)切換中文英文!

        配置國際化解析

        在Spring中有一個(gè)國際化的Locale (區域信息對象);里面有一個(gè)叫做LocaleResolver (獲取區域信息對象)的解析器!

        我們去我們webmvc自動(dòng)配置文件,尋找一下!看到SpringBoot默認配置:

        @Bean
        @ConditionalOnMissingBean
        @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
        public LocaleResolver localeResolver() {
           // 容器中沒(méi)有就自己配,有的話(huà)就用用戶(hù)配置的
           if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
               return new FixedLocaleResolver(this.mvcProperties.getLocale());
           }
           // 接收頭國際化分解
           AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
           localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
           return localeResolver;
        }

        AcceptHeaderLocaleResolver 這個(gè)類(lèi)中有一個(gè)方法

        public Locale resolveLocale(HttpServletRequest request) {
            Locale defaultLocale = this.getDefaultLocale();
            // 默認的就是根據請求頭帶來(lái)的區域信息獲取Locale進(jìn)行國際化
            if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
                return defaultLocale;
            } else {
                Locale requestLocale = request.getLocale();
                List<Locale> supportedLocales = this.getSupportedLocales();
                if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
                    Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
                    if (supportedLocale != null) {
                        return supportedLocale;
                    } else {
                        return defaultLocale != null ? defaultLocale : requestLocale;
                    }
                } else {
                    return requestLocale;
                }
            }
        }

        那假如我們現在想點(diǎn)擊鏈接讓我們的國際化資源生效,就需要讓我們自己的Locale生效!

        我們去自己寫(xiě)一個(gè)自己的LocaleResolver,可以在鏈接上攜帶區域信息!

        修改一下前端頁(yè)面的跳轉連接:

        <!-- 這里傳入參數不需要使用 ?使用 (key=value)-->
        <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}" rel="external nofollow" >中文</a>
        <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}" rel="external nofollow" >English</a>

        我們去寫(xiě)一個(gè)處理的組件類(lèi)!

        package com.kuang.component;
        
        import org.springframework.util.StringUtils;
        import org.springframework.web.servlet.LocaleResolver;
        
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.util.Locale;
        
        //可以在鏈接上攜帶區域信息
        public class MyLocaleResolver implements LocaleResolver {
        
            //解析請求
            @Override
            public Locale resolveLocale(HttpServletRequest request) {
        
                String language = request.getParameter("l");
                Locale locale = Locale.getDefault(); // 如果沒(méi)有獲取到就使用系統默認的
                //如果請求鏈接不為空
                if (!StringUtils.isEmpty(language)){
                    //分割請求參數
                    String[] split = language.split("_");
                    //國家,地區
                    locale = new Locale(split[0],split[1]);
                }
                return locale;
            }
        
            @Override
            public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
        
            }
        }

        為了讓我們的區域化信息能夠生效,我們需要再配置一下這個(gè)組件!在我們自己的MvcConofig下添加bean;

        @Bean
        public LocaleResolver localeResolver(){
            return new MyLocaleResolver();
        }

        我們重啟項目,來(lái)訪(fǎng)問(wèn)一下,發(fā)現點(diǎn)擊按鈕可以實(shí)現成功切換!搞定收工!

        注意點(diǎn)

        4、登錄+攔截器

        4.1、登錄

        禁用模板緩存

        說(shuō)明:頁(yè)面存在緩存,所以我們需要禁用模板引擎的緩存

        #禁用模板緩存 
        spring.thymeleaf.cache=false

        模板引擎修改后,想要實(shí)時(shí)生效!頁(yè)面修改完畢后,IDEA小技巧 : Ctrl + F9 重新編譯!即可生效!

        登錄

        我們這里就先不連接數據庫了,輸入任意用戶(hù)名都可以登錄成功!

        1、我們把登錄頁(yè)面的表單提交地址寫(xiě)一個(gè)controller!

        <form class="form-signin" th:action="@{/user/login}" method="post">
         //這里面的所有表單標簽都需要加上一個(gè)name屬性 
            
        </form>

        2、去編寫(xiě)對應的controller

        @Controller
        public class LoginController {
            @RequestMapping("/user/login")
            public String login(
                    @RequestParam("username") String username ,
                    @RequestParam("password") String password,
                    Model model){
                //具體的業(yè)務(wù)
                if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
                    return "redirect:/main.html";
                }
                else{
                    //告訴用戶(hù),你登錄失敗
                    model.addAttribute("msg","用戶(hù)名或者密碼錯誤!");
                    return "index";
                }
            }
        }

        OK ,測試登錄成功!

        3、登錄失敗的話(huà),我們需要將后臺信息輸出到前臺,可以在首頁(yè)標題下面加上判斷

        <!--判斷是否顯示,使用if, ${}可以使用工具類(lèi),可以看thymeleaf的中文文檔--> 
        <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"> 
        </p>

        重啟登錄失敗測試:

        優(yōu)化,登錄成功后,由于是轉發(fā),鏈接不變,我們可以重定向到首頁(yè)!

        4、我們再添加一個(gè)視圖控制映射,在我們的自己的MyMvcConfifig中:

        registry.addViewController("/main.html").setViewName("dashboard");

        5、將 Controller 的代碼改為重定向;

        //登錄成功!防止表單重復提交,我們重定向 
        return "redirect:/main.html";

        重啟測試,重定向成功!后臺主頁(yè)正常顯示!

        4.2、登錄攔截器

        但是又發(fā)現新的問(wèn)題,我們可以直接登錄到后臺主頁(yè),不用登錄也可以實(shí)現!怎么處理這個(gè)問(wèn)題呢?我

        們可以使用攔截器機制,實(shí)現登錄檢查!

        1、在LoginController添加serssion

        session.setAttribute("loginUser",username);

        2、自定義一個(gè)攔截器:

        //自定義攔截器
        public class LoginHandlerInterceptor implements HandlerInterceptor {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                //獲取 loginUser 信息進(jìn)行判斷
                Object user = request.getSession().getAttribute("loginUser");
                if(user == null){//未登錄,返回登錄頁(yè)面
                    request.setAttribute("msg","沒(méi)有權限,請先登錄");
                    request.getRequestDispatcher("/index.html").forward(request,response);
                    return false;
                }else{
                    //登錄,放行
                    return true;
                }
            }
        }

        3、然后將攔截器注冊到我們的SpringMVC配置類(lèi)當中!

        @Override
            public void addInterceptors(InterceptorRegistry registry) {
                // 注冊攔截器,及攔截請求和要剔除哪些請求!
                // 我們還需要過(guò)濾靜態(tài)資源文件,否則樣式顯示不出來(lái)
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/user/login","/","/css/*","/img/**","/js/**");
        }

        4、我們然后在后臺主頁(yè),獲取用戶(hù)登錄的信息

        <!--后臺主頁(yè)顯示登錄用戶(hù)的信息-->
        [[${session.loginUser}]] <!--$取EL表達式-->

        然后我們登錄測試攔截!完美!

        5、展示員工列表

        5.1、員工列表頁(yè)面跳轉

        我們在主頁(yè)點(diǎn)擊Customers,就顯示列表頁(yè)面;我們去修改下

        1、將首頁(yè)的側邊欄Customers改為員工管理

        2、a鏈接添加請求

        <a class="nav-link" th:href="@{/emps}" rel="external nofollow"  rel="external nofollow" >員工管理</a>

        3、將list放在emp文件夾下

        4、編寫(xiě)處理請求的controller

        //員工列表
        @Controller
        public class EmployeeController {
        
            @Autowired
            EmployeeDao employeeDao;
        
            @RequestMapping("/emps")
            public String list(Model model){
                Collection<Employee> employees = employeeDao.getALL();
                model.addAttribute("emps",employees);
                return "emp/list";
            }
        }

        我們啟動(dòng)項目,測試一下看是否能夠跳轉,測試OK!我們只需要將數據渲染進(jìn)去即可!

        但是發(fā)現了一個(gè)問(wèn)題,側邊欄和頂部都相同,我們是不是應該將它抽取出來(lái)呢?

        5.2、Thymeleaf公共頁(yè)面元素抽取

        步驟:

        1、抽取公共片段 th:fragment 定義模板名

        2、引入公共片段 th:insert 插入模板名

        實(shí)現:

        1、我們來(lái)抽取一下,使用list列表做演示!我們要抽取頭部nav標簽,我們在dashboard中將nav部分定

        義一個(gè)模板名;

        <!--頂部導航欄-->
        <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
            <a class="navbar-brand col-sm-3 col-md-2 mr-0"  rel="external nofollow"  rel="external nofollow" >[[${session.loginUser}]]</a> <!--$取EL表達式-->
            <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
            <ul class="navbar-nav px-3">
                <li class="nav-item text-nowrap">
                    <a class="nav-link"  rel="external nofollow"  rel="external nofollow" >注銷(xiāo)</a>
                </li>
            </ul>
        </nav>

        2、然后我們在list頁(yè)面中去引入,可以刪掉原來(lái)的nav

        <!--引入抽取的topbar--> 
        <!--模板名 : 會(huì )使用thymeleaf的前后綴配置規則進(jìn)行解析 使用~{模板::標簽名}-->
        <!--頂部導航欄-->
        <div th:insert="~{dashboard::topbar}"></div>

        3、啟動(dòng)再次測試,可以看到已經(jīng)成功加載過(guò)來(lái)了!

        說(shuō)明:

        除了使用insert插入,還可以使用replace替換,或者include包含,三種方式會(huì )有一些小區別,可以見(jiàn)名

        知義;

        我們使用replace替換,可以解決div多余的問(wèn)題,可以查看thymeleaf的文檔學(xué)習

        側邊欄也是同理,當做練手,可以也同步一下!

        定義模板:

        <!--側邊欄-->
        <nav th:fragment="sitebar" class="col-md-2 d-none d-md-block bg-light sidebar">

        然后我們在list頁(yè)面中去引入:

        <!--頂部導航欄-->
        <div th:replace="~{commons/commons::topbar}"></div>
        <!--側邊欄-->
        <div th:replace="~{commons/commons::sidebar}"></div>

        啟動(dòng)再試試,看效果!

        我們發(fā)現一個(gè)小問(wèn)題,側邊欄激活的問(wèn)題,它總是激活第一個(gè);按理來(lái)說(shuō),這應該是動(dòng)態(tài)的才對!

        為了重用更清晰,我們建立一個(gè)commons文件夾,專(zhuān)門(mén)存放公共頁(yè)面;

        我們去頁(yè)面中引入一下

        <a th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/index.html}" rel="external nofollow" >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
                <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                <polyline points="9 22 9 12 15 12 15 22"></polyline>
            </svg>
            首頁(yè) <span class="sr-only">(current)</span>
        </a>
        
        <a th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/emps}" rel="external nofollow"  rel="external nofollow" >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
                <circle cx="9" cy="21" r="1"></circle>
                <circle cx="20" cy="21" r="1"></circle>
                <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
            </svg>
            員工管理
        </a>

        我們先測試一下,保證所有的頁(yè)面沒(méi)有出問(wèn)題!ok!

        側邊欄激活問(wèn)題:

        1、將首頁(yè)的超鏈接地址改到項目中

        2、我們在a標簽中加一個(gè)判斷,使用class改變標簽的值;

        <div th:replace="~{commons/commons::topbar(active='main.html')}"></div>
        <div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>

        3、修改請求鏈接

        <thead>
            <tr>
                <th>id</th>
                <th>lastName</th>
                <th>email</th>
                <th>gender</th>
                <th>department</th>
                <th>birth</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="emp:${emps}">
                <td th:text="${emp.getId()}"></td>
                <td th:text="${emp.getLastName()}"></td>
                <td th:text="${emp.getEmail()}"></td>
                <td th:text="${emp.getGender()==0?'女':'男'}"></td>
                <td th:text="${emp.department.getDepartmentName()}"></td>
                <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
                <td>
                    <button class="btn btn-sm btn-primary">編輯</button>
                    <button class="btn btn-sm btn-danger">刪除</button>
                </td>
            </tr>
        </tbody>

        4、我們刷新頁(yè)面,去測試一下,OK,動(dòng)態(tài)激活搞定!

        5.3、員工信息頁(yè)面展示

        現在我們來(lái)遍歷我們的員工信息!順便美化一些頁(yè)面,增加添加,修改,刪除的按鈕!

        <h2><a class="btn btn-sm btn-success" th:href="@{/emp}" rel="external nofollow" >添加員工</a></h2>

        OK,顯示全部員工OK!

        6、添加員工實(shí)現

        6.1、表單及細節處理

        1、將添加員工信息改為超鏈接

        //to員工添加頁(yè)面 
        @GetMapping("/emp") 
        public String toAddPage(){ 
            return "emp/add"; 
        }

        2、編寫(xiě)對應的controller

        <form th:action="@{/emp}" method="post" >
            <div class="form-group" ><label>LastName</label>
                <input class="form-control" placeholder="kuangshen" type="text" name="lastName">
            </div>
            <div class="form-group" ><label>Email</label>
                <input class="form-control" placeholder="24736743@qq.com" type="email" name="email">
            </div>
            <div class="form-group"><label>Gender</label><br/>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" name="gender" type="radio" value="1">
                    <label class="form-check-label">男</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" name="gender" type="radio" value="0">
                    <label class="form-check-label">女</label>
                </div>
            </div>
            <div class="form-group" ><label>department</label>
                <select class="form-control" name="department.id">
                    <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
                </select>
            </div>
            <div class="form-group" >
                <label >Birth</label>
                <input class="form-control" placeholder="kuangstudy" type="text" name="birth">
            </div>
            <button class="btn btn-primary" type="submit">添加</button>
        </form>

        3、添加前端頁(yè)面;復制list頁(yè)面,修改即可

        bootstrap官網(wǎng)文檔 : https://v4.bootcss.com/docs/4.0/components/forms/

        我們去可以里面找自己喜歡的樣式!我這里給大家提供了編輯好的:

        @GetMapping("/emp")
        public String toAddPage(Model model){
            //查詢(xún)所有的部門(mén)信息
            Collection<Department> departments = departmentDao.getDepartments();
            model.addAttribute("departments",departments);
            return "emp/add";
        }

        4、部門(mén)信息下拉框應該選擇的是我們提供的數據,所以我們要修改一下前端和后端

        Controller

        <select class="form-control" name="department.id">
            <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
        </select>

        前端

        <form th:action="@{/emp}" method="post"> 1

        OK,修改了controller,重啟項目測試!

        6.2、具體添加功能

        1、修改add頁(yè)面form表單提交地址和方式

        <form th:action="@{/emp}" method="post"> 

        2、編寫(xiě)controller;

        //員工添加功能
        //接收前端傳遞的參數,自動(dòng)封裝成為對象[要求前端傳遞的參數名,和屬性名一致]
        @PostMapping ("/emp")
        public String addEmp(Employee employee){
            //保存員工的信息
            System.out.println(employee);
            employeeDao.save(employee);
            // 回到員工列表頁(yè)面,可以使用redirect或者forward,就不會(huì )被視圖解析器解析
            return "redirect:/emps";
        }

        回憶:重定向和轉發(fā)以及 /的問(wèn)題?

        時(shí)間格式問(wèn)題

        生日我們提交的是一個(gè)日期 , 我們第一次使用的 / 正常提交成功了,后面使用 - 就錯誤了,所以這里面

        應該存在一個(gè)日期格式化的問(wèn)題;

        SpringMVC會(huì )將頁(yè)面提交的值轉換為指定的類(lèi)型,默認日期是按照 / 的方式提交 ; 比如將2019/01/01

        轉換為一個(gè)date對象。

        那思考一個(gè)問(wèn)題?我們能不能修改這個(gè)默認的格式呢?

        這個(gè)在配置類(lèi)中,所以我們可以自定義的去修改這個(gè)時(shí)間格式化問(wèn)題,我們在我們的配置文件中修改一

        下;

        spring.mvc.date-format=yyyy-MM-dd

        這樣的話(huà),我們現在就支持 - 的格式了,但是又不支持 / 了 , 2333吧

        測試OK!

        7、修改員工信息

        邏輯分析:

        我們要實(shí)現員工修改功能,需要實(shí)現兩步;

        1、點(diǎn)擊修改按鈕,去到編輯頁(yè)面,我們可以直接使用添加員工的頁(yè)面實(shí)現

        2、顯示原數據,修改完畢后跳回列表頁(yè)面!

        實(shí)現

        1、我們去實(shí)現一下,首先修改跳轉鏈接的位置;

        <a class="btn btn-sm btn-primary" th:href="@{/emp

        免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。

        久久久久亚洲AV成人人电影软件| 亚洲中文字幕久久无码精品| 少妇激情AV一区二区| 亚洲精品无码久久不卡| 婬荡的女教师| 亚洲A∨无码男人的天堂|