restful風格的增刪改查

注意

  • 如果靜態資源放到了靜態資源文件夾下卻無法訪問,請檢查一下是不是在自定義的配置類上加了@EnableWebMvc注解
  • templete文件夾不是靜態資源的文件夾,默認是無法訪問的,所以要添加視圖映射
package cn.xxxxxx.hellospringbootweb.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index").setViewName("login");registry.addViewController("/index.html").setViewName("login");}
}

?i18n國際化

  1. 編寫國際化配置文件,抽取頁面需要顯示的國際化消息

    創建i18n文件夾存放配置文件,文件名格式為基礎名(login)+語言代碼(zh)+國家代碼(CN)

  2. 在配置文件中添加國際化文件的位置和基礎名,如果配置文件中沒有配置基礎名,就在類路徑下找基礎名為message的配置文件

    spring.messages.basename=i18n.login
    1. 點擊切換語言? ? 修改頁面,點擊連接攜帶語言參數
    <a class="btn btn-sm" href="?l=zh_CN">中文</a>
    <a class="btn btn-sm" href="?l=en_US">English</a>

實現登陸功能

1,提供登陸的Controller

@Controller
public class UserController {@PostMapping("/user/login")public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {if (!StringUtils.isEmpty(username) && "123456".equals(password)) {//登錄成功,把用戶信息方法哦session中,防止表單重復提交,重定向到后臺頁面session.setAttribute("loginUser", username);return "redirect:/main.html";}//登錄失敗,返回到登錄頁面model.addAttribute("msg", "用戶名或密碼錯誤!");return "login";}
}

2,修改表單的提交地址,輸入框添加name值與參數名稱相對應

        <form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post"><img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"><h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1><label class="sr-only">Username</label><input type="text" name="username" class="form-control" th:placeholder="#{login.username}" placeholder="Username" autofocus=""><label class="sr-only">Password</label><input type="password" name="password" class="form-control" th:placeholder="#{login.password}" placeholder="Password" required=""><div class="checkbox mb-3"><label><input type="checkbox" value="remember-me"> [[#{login.remember}]]</label></div><button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button><p class="mt-5 mb-3 text-muted">? 2017-2018</p><a class="btn btn-sm" href="?l=zh_CN">中文</a><a class="btn btn-sm" href="?l=en_US">English</a></form>

3,由于登陸失敗是轉發,所以得修改靜態資源的請求路徑,在其中添加模版引擎

<link  href="asserts/css/bootstrap.min.css" th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">

4,添加登陸頁面的顯示,將msg傳回主頁面

<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--msg存在才顯示該p標簽-->
<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}" style="color: red"></p>

修改頁面使其立即生效

在配置文件里面添加如下的命令,在頁面修改完成之后,按快捷鍵ctrl+f9,重新編譯

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

攔截器進行登陸檢查

1,實現攔截器

package cn.xxxxxx.hellospringbootweb.interceptor;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class LoginHandlerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object loginUser = request.getSession().getAttribute("loginUser");if (loginUser == null) {//未登錄,攔截,并轉發到登錄頁面request.setAttribute("msg", "您還沒有登錄,請先登錄!");request.getRequestDispatcher("/index").forward(request, response);return false;}return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}

2,注冊攔截器

package cn.clboy.hellospringbootweb.config;import cn.clboy.hellospringbootweb.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyMvcConfig implements WebMvcConfigurer {//定義不攔截路徑private static final String[] excludePaths = {"/", "/index", "/index.html", "/user/login", "/asserts/**"};@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("/main.html").setViewName("dashboard");}@Beanpublic LocaleResolver localeResolver() {return new MyLocaleResolver();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {//添加不攔截的路徑,SpringBoot已經做好了靜態資源映射,所以我們不用管registry.addInterceptor(new LoginHandlerInterceptor()).excludePathPatterns(excludePaths);}
}

注意:在spring2.0+的版本中,只要用戶自定義了攔截器,則靜態資源會被攔截。但是在spring1.0+的版本中,是不會攔截靜態資源的。因此我們需要將靜態資源排除到攔截器的攔截路徑之外

案例,實現員工的增刪改查

實驗功能請求URI請求方式
查詢所有員工empsGET
查詢某個員工(來到修改頁面)emp/1GET
來到添加頁面empGET
添加員工empPOST
來到修改頁面(查出員工進行信息回顯)emp/1GET
修改員工empPUT
刪除員工emp/1DELETE
  1. 為了頁面結構清晰,在template文件夾下新建emp文件夾,將list.html移動到emp文件夾下

  2. 將dao層和實體層java代碼復制到項目中daoentities

  3. 添加員工controller,實現查詢員工列表的方法

    @Controller
    public class EmpController {@Autowiredprivate EmployeeDao employeeDao;@GetMapping("/emps")public String emps(Model model) {Collection<Employee> empList = employeeDao.getAll();model.addAttribute("emps", empList);return "emp/list";}}
  4. 修改后臺頁面,更改左側的側邊欄,并修改請求路徑
    <li class="nav-item"><a class="nav-link" th:href="@{/emps}"><svg .....>......</svg>員工列表</a>
    </li>

thymeleaf公共頁面元素抽取(參考官方文檔)

  • ~{templatename::selector}:模板名::選擇器
  • ~{templatename::fragmentname}:模板名::片段名
/*公共代碼片段*/
<footer th:fragment="copy">&copy; 2011 The Good Thymes Virtual Grocery
</footer>/*引用代碼片段*/
<div th:insert="~{footer :: copy}"></di/*(?{...}包圍是完全可選的,所以上?的代碼 將等價于:*/
<div th:insert="footer :: copy"></di

三種引入公共片段的th屬性:

  • th:insert:將公共片段整個插入到聲明引入的元素中
  • th:replace:將聲明引入的元素替換為公共片段
  • th:include:將被引入的片段的內容包含進這個標簽中

后臺頁面的抽取

1,將后臺主頁中的頂部導航欄作為片段,在list中引入

        <nav th:fragment="topbar" class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"><a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Company name</a><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" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a></li></ul></nav>

2,list.html

<body><div th:replace="dashboard::topbar"></div>......

3,使用選擇器的方式抽取左側邊欄的代碼,就是我們將不同html文件的公共部分抽取出來,作為一個模版,其余需要的html文件只需要引入即可使用。比如現在我們將名稱為sidebar的模版放在dashboard.html里面,而在list.html里面進行復用。

<!--dashboard.html-->
<div class="container-fluid"><div class="row"><nav id="sidebar" class="col-md-2 d-none d-md-block bg-light sidebar" ......
<!--list.html-->
<div class="container-fluid"><div class="row"><div th:replace="dashboard::#sidebar"></div>......

4,顯示員工數據,添加增刪改按鈕

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><h2><button class="btn btn-sm btn-success">添加員工</button></h2><div class="table-responsive"><table class="table table-striped table-sm"><thead><tr><th>員工號</th><th>姓名</th><th>郵箱</th><th>性別</th><th>部門</th><th>生日</th><th>操作</th></tr></thead><tbody><tr th:each="emp:${emps}"><td th:text="${emp.id}"></td><td th:text="${emp.lastName}"></td><td th:text="${emp.email}"></td><td th:text="${emp.gender}==1?'男':'女'"></td><td th:text="${emp.department.departmentName}"></td><td th:text="${#dates.format(emp.birth,'yyyy-MM-dd')}"></td><td><button class="btn btn-sm btn-primary">修改</button><button class="btn btn-sm btn-danger">刪除</button></td></tr></tbody></table></div></main>

5,員工添加頁面 add.html

......
<body>
<div th:replace="commons/topbar::topbar"></div><div class="container-fluid"><div class="row"><div th:replace="commons/sidebar::#sidebar(currentURI='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><form><div class="form-group"><label>LastName</label><input name="lastName" type="text" class="form-control" placeholder="zhangsan"></div><div class="form-group"><label>Email</label><input  name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><select name="department.id" class="form-control"><option th:each="dept:${departments}" th:text="${dept.departmentName}" th:value="${dept.id}"></option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="zhangsan"></div><button type="submit" class="btn btn-primary">添加</button></form></main></div>
</div>
......

6,點擊鏈接,跳轉到添加頁面

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

7,EmpController添加映射方法

    @Autowiredprivate DepartmentDao departmentDao;@GetMapping("/emp")public String toAddPage(Model model) {//準備部門下拉框數據Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("departments",departments);return "emp/add";}

8, 修改頁面遍歷添加下拉選項

<select class="form-control"><option th:each="dept:${departments}" th:text="${dept.departmentName}"></option>
</select>

9,表單提交,添加員工

<form th:action="@{/emp}" method="post">
    @PostMapping("/emp")public String add(Employee employee) {System.out.println(employee);//模擬添加到數據庫employeeDao.save(employee);//添加成功重定向到列表頁面return "redirect:/emps";}

10,日期格式的修改

表單提交的格式必須是yyyy/MM/dd的格式,可以在配置文件中修改格式

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

員工修改

  1. 點擊按鈕跳轉到編輯頁面
     <a th:href="@{/emp/}+${emp.id}" class="btn btn-sm btn-primary">修改</a>
  2. 添加編輯頁面,將表單的提交方式設置為post方式,提供_method參數
    <body>
    <div th:replace="commons/topbar::topbar"></div><div class="container-fluid"><div class="row"><div th:replace="commons/sidebar::#sidebar(currentURI='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><form th:action="@{/emp}" method="post"><!--員工id--><input type="hidden" name="id" th:value="${emp.id}"><!--http請求方式--><input type="hidden" name="_method" value="put"><div class="form-group"><label>LastName</label><input name="lastName" th:value="${emp.lastName}" type="text" class="form-control" placeholder="zhangsan"></div><div class="form-group"><label>Email</label><input  name="email" th:value="${emp.email}" type="email" class="form-control" placeholder="zhangsan@atguigu.com"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp.gender==1}"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp.gender==0}"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><select name="department.id" class="form-control"><option th:each="dept:${departments}" th:value="${dept.id}" th:selected="${dept.id}==${emp.department.id}" th:text="${dept.departmentName}"></option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${#dates.format(emp.birth,'yyyy-MM-dd')}"></div><button type="submit" class="btn btn-primary">添加</button></form></main></div>
    </div>......
  3. controller轉發到編輯頁面,回顯員工信息
        @GetMapping("/emp/{id}")public String toEditPage(@PathVariable Integer id, Model model) {Employee employee = employeeDao.get(id);//準備部門下拉框數據Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("emp", employee).addAttribute("departments", departments);return "emp/edit";}
  4. 提交表單修改員工的信息
        @PutMapping("/emp")public String update(Employee employee) {employeeDao.save(employee);return "redirect:/emps";}

員工刪除

  1. 點擊刪除提交發出delete請求
        @DeleteMapping("/emp/{id}")public String delete(@PathVariable String id){employeeDao.delete(id);return "redirect:/emps";}
  2. 如果提示不支持POST請求,在確保代碼無誤的情況下查看是否配置啟動HiddenHttpMethodFilter
  3. 這個好像是2.0版本以后修改的
    spring.mvc.hiddenmethod.filter.enabled=true
  4. 如果刪除不掉,請修改EmployeeDao,把String轉為Integer類型

        public void delete(String id) {employees.remove(Integer.parseInt(id));}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/447360.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/447360.shtml
英文地址,請注明出處:http://en.pswp.cn/news/447360.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

歷史上最有影響力的10款開源項目

開源是大趨勢&#xff0c;開源軟件也在越來越多的出現在日常電腦桌面上&#xff0c;如Firefox瀏覽器、Ubuntu操作系統等。人們選擇開源軟件的原因&#xff0c;主要有低成本、安全無病毒侵害、更加透明和開放等。按照大多數的開源協議如GPL&#xff0c;開源軟件允許自由分發。在…

SpringBoot默認的錯誤處理機制

錯誤處理機制&#xff1a; 訪問一個不存在的頁面時&#xff0c;或者程序拋出異常時 默認效果 瀏覽器返回一個錯誤的頁面&#xff0c;注意查看瀏覽器發送請求的請求頭可以使用專業的軟件比如postman分析返回的json數據 springboot錯誤處理的自動配置信息 主要給日容器中注冊…

GitHub政府用戶破萬:開源成重塑政府新手段

據GitHub官方博客介紹&#xff0c;目前GitHub上的各地政府用戶數量已經達到1萬個&#xff01; 2009年&#xff0c;紐約參議院正式入駐GitHub公開部分技術資料與文檔&#xff0c;成為GitHub上的第一個政府組織。隨后&#xff0c;美國華盛頓特區、邁阿密、芝加哥、紐約&#xff…

配置嵌入式Servlet容器

如何定制和修改Servlet容器的相關配置 修改定制和修改Servlet容器的相關配置 server.port8081 server.context-path/crudserver.tomcat.uri-encodingUTF-8//通用的Servlet容器設置 server.xxx //Tomcat的設置 server.tomcat.xxx 編寫一個EmbeddedServletContainerCustomizer&…

云OS:Linux在桌面打翻身仗的機會?

不可否認&#xff0c;Chrome OS取得了驚人的增長。Chromebook自發行以來&#xff0c;迅速席卷全球&#xff0c;常年位居最暢銷筆記本榜首。這款基于Linux的筆記本在合適時間提供了合適的解決方案。很多情況下&#xff0c;云不僅僅是一個可選項&#xff0c;而是一個最優選項。Li…

Docker容器基本使用

Dcoker Docker是一個開源的應用容器引擎&#xff0c;是一個輕量級別的容器技術Dcoker支持將軟件編譯成一個鏡像&#xff1b;然后在鏡像中對各種軟件做好配置&#xff0c;再將鏡像發布出去&#xff0c;供別人使用運行中的鏡像稱為容器&#xff0c;容器的啟動是非常快速的核心概…

為什么35歲的C++依然能主導編程世界

早在1979年&#xff0c;Bjarne Stroustrup設計了C編程語言&#xff0c;并且C很快成為了無處不在的通用系統編程語言。現在盡管有Java、Javascript、Python、Go&#xff0c;甚至是蘋果的Swift和它競爭&#xff0c;但C依然處于主導編程世界的地位。 今天在Morgan Stanley的科技訪…

SpringBoot整合JPA

添加依賴 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId&…

為什么說選擇正確的編程語言很重要,以及如何正確的選擇

幾個月前&#xff0c;一個同事問我&#xff0c;應該如何選擇編程語言&#xff0c;或者有沒有什么固定的選擇模式&#xff0c;當時我便打算寫點什么。上周在硅谷開會&#xff0c;這我是第一次跟“hack3rs”的創業狂以及技術狂們打交道。我學會了很多前所未聞的臟話&#xff0c;也…

細數開源歷史上的十個重大事件

開放源碼&#xff08;開源&#xff09;的精神在于使用者可以使用、復制、散布、研究和改進軟件。這可以追溯到20世紀60年代&#xff0c;至今已有半個世紀了。雖然下面所列舉的不都是專門的開源產品&#xff0c;但還是在開源發展的進程中有著巨大的影響。開放源碼&#xff08;開…

科研必備學士搜索引擎推薦

綜合性學術搜索引擎 中國知網萬方數據百度學術谷歌學術谷歌學術鏡像Web of ScienceEiVillage2EIsevier電子期刊SpringerSemanticScholar 圖片文獻檢索方法 CNKI 期刊查詢 DOAJSocolarOpenDOAROALIB開放存取圖書館 碩博論文搜索下載 上海交大鏡像網站歐洲學位論文庫 國外電子…

如何寫一篇論文

文獻綜述的地位 體現了學術研究的繼承性 文獻綜述的寫作是由學術研究的繼承性決定的&#xff0c;因為繼承是創新的基礎和前提。文獻綜述部分要澄清所研究問題“從哪里來&#xff0c;到哪里去” 。這部分主要是繼承&#xff0c;是梳理前人的成果并找出其內在的邏輯關系和演進的規…

深度卷積神經網絡CNNs的多GPU并行框架及其應用

摘要&#xff1a;本文是騰訊深度學習系列文章之一&#xff0c;主要聚焦于騰訊深度學習平臺&#xff08;Tencent Deep Learning Platform&#xff09;中深度卷積神經網絡Deep CNNs的多GPU模型并行和數據并行框架。 【編者按】深度卷積神經網絡有著廣泛的應用場景&#xff0c;本…

如果誤刪谷歌瀏覽器的書簽,怎么恢復

如果是Mac用戶&#xff0c;command和z一直恢復就可以 同理&#xff0c;windows用戶&#xff0c;也可以使用撤銷鍵&#xff0c;ctrlz即可

55分鐘學會正則表達式

正則表達式是一種查找以及字符串替換操作。正則表達式在文本編輯器中廣泛使用&#xff0c;比如正則表達式被用于&#xff1a; 檢查文本中是否含有指定的特征詞找出文中匹配特征詞的位置從文本中提取信息&#xff0c;比如&#xff1a;字符串的子串修改文本 與文本編輯器相似&a…

線程安全和對應的核心概念

線程安全 線程安全的概念&#xff1a;當多個線程訪問某一個類&#xff08;對象和方法&#xff09;時&#xff0c;這個類始終都能表現出正確的行為&#xff0c;那么這個類&#xff08;對象或者方法&#xff09;就是線程安全的synchronized&#xff1a;可以在任意對象及方法上加…

JDK Unsafe類的使用與CAS原子特性

JDK Unsafe類的使用與CAS原子特性 Java.util.concurrent.atomic包&#xff0c;其中包含了大量使用到Unsafe這個類Java不能直接訪問操作系統的底層&#xff0c;而是通過本地方法來訪問。 Unsafe類提供了硬件級別的原子操作&#xff0c;主要提供了以下功能 內存操作字段的定位和…

寫軟件不是造汽車

寫軟件和做其他事情是不一樣的。當我們制造別的東西的時候——像汽車、玩具、椅子、畫作、甚至包括數字產品如平面圖片和3D模型——我們做出來的成品就是最終的結果。而開發軟件則不是&#xff0c;我們做出來的產品永遠不可能有最終的結果——我們需要向計算機解釋如何根據任意…

線程池核心概述

線程池核心概述 Executors工廠類使用 Executors工廠類底層源碼分析詳解 ThreadPoolExecutor自定義線程池 ThreadPoolExecutor拒絕策略詳解 計算機密集型與IO密集型詳解 如何正確的使用線程池…

網站盈利的10種方式

如果你有自己的網站&#xff0c;而且已經有了不少的流量&#xff0c;你肯定會開始考慮如何通過這個網站來掙一些錢。 在這篇文章中&#xff0c;我會向大家介紹網站最常見的10種盈利方式。 1.按點擊付費廣告 在網站上展示一個按點擊付費的廣告橫幅是最簡單的盈利方式&#xff…