長(zhǎng)春網(wǎng)站建設(shè)案例天津快速關(guān)鍵詞排名
前期回顧
- springboot項(xiàng)目常見(jiàn)的配置文件類型有哪些?哪種類型的優(yōu)先級(jí)最高
yml properties yaml
- 讀取配置文件里的數(shù)據(jù)用什么注解?
@value
restful風(fēng)格
RESTful 風(fēng)格與傳統(tǒng)的 HTTP 請(qǐng)求方式相比,更加簡(jiǎn)潔,安全,能隱藏資源的訪問(wèn)行為,無(wú)法從訪問(wèn)地址得知對(duì)資源是何種操作
可見(jiàn)很多 RESTful 風(fēng)格的訪問(wèn)地址都是一樣的,只用行為動(dòng)作區(qū)分了不同的訪問(wèn),對(duì)外隱藏了真實(shí)的操作。此外,資源描述部分一般用復(fù)數(shù),如 books,當(dāng)然這種操作是只是一種約定,不是規(guī)范,但大多數(shù)人都這樣做。
@RestController
@RequestMapping("/users")
public class UserController {@PostMappingpublic String addUser(@RequestBody UserInfo userInfo){System.out.println("新增用戶信息:"+userInfo);return "新增用戶成功";}@DeleteMapping("/{id}")public String del(@PathVariable Integer id){System.out.println("刪除用戶ID:"+id);return "刪除用戶成功";}@PutMappingpublic String update(@RequestBody UserInfo userInfo){System.out.println("修改后");return "修改用戶成功";}@GetMapping("/{id}")public String getUser(@PathVariable Integer id){System.out.println("用戶ID:"+id);return "查詢用戶ID成功!";}@GetMappingpublic String getUsers(){System.out.println("查詢所有的用戶");return "查詢所有的用戶";}}
利用postman測(cè)試
{"username":"zhangsan","password":"z3","mobilephone":"15336574540"
}
靜態(tài)資源訪問(wèn)
默認(rèn)靜態(tài)資源訪問(wèn)
Spring Boot 規(guī)定了靜態(tài)資源可以放在以下 5 個(gè)目錄中的任意一個(gè)下面:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/
Spring Boot 項(xiàng)目創(chuàng)建完成后默認(rèn)情況下提供了classpath:/static/目錄,一般情況下在此放置靜態(tài)資源即可
自定義靜態(tài)資源
1.在application.yml配置
web:upload-path: D:/upimgs/
spring:mvc:static-path-pattern: /**web:resources:static-locations:file:${web.upload-path},classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
2.配置類的方式
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/","file:D:/upimgs/");}
}
路徑映射
在 Spring Boot 的 Web 項(xiàng)目中,所有頁(yè)面都需要通過(guò)控制器才能訪問(wèn)到,包括沒(méi)有數(shù)據(jù)的頁(yè)面。對(duì)于這種只是完成簡(jiǎn)單的跳轉(zhuǎn)的沒(méi)有數(shù)據(jù)的頁(yè)面,可以直接配置路徑映射,不再經(jīng)過(guò)控制器。
1.導(dǎo)入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.yml中添加thymeleaf的配置
spring:thymeleaf:prefix: classpath:/templates/suffix: .html
默認(rèn)就是這樣,所以可以省略不寫
3.在項(xiàng)目的 resource/ templates 目錄下創(chuàng)建 add.html 文件和 register.html 文件
4.在項(xiàng)目的 MyWebMvcConfig 配置類中重寫 addViewControlles 方法
@Override
protected void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/add").setViewName("add");registry.addViewController("/register").setViewName("register");
}
5.運(yùn)行測(cè)試,瀏覽器訪問(wèn) http://localhost:8080/add,結(jié)果訪問(wèn)到了 add.html 頁(yè)面, 訪問(wèn) http://localhost:8080/register,結(jié)果訪問(wèn)到了 register.html 頁(yè)面
CORS 跨域資源訪問(wèn)
回顧一下瀏覽器的同源策略
假設(shè)后端的主頁(yè) URL 是 http://sike.com/index.html
CORS 基礎(chǔ)
CORS 是一個(gè) W3C 的一種跨域資源共享技術(shù)標(biāo)準(zhǔn),目的是為了解決前端的跨域請(qǐng)求問(wèn)題,是英文 Cross-origin resource sharing 的縮寫,全稱是“跨域資源共享”,它允許瀏覽器向跨源(協(xié)議 + 域名 + 端口)服務(wù)器,發(fā)出 XMLHttpRequest 請(qǐng)求,從而克服了 AJAX 只能同源使用的限制。
解決方案
1.@CrossOrigin 注解實(shí)現(xiàn)方案
直接在控制器需要跨域訪問(wèn)的方法上面添加@CrossOrigin 注解,并配置跨域?qū)傩?#xff0c;主要屬性有:
- value:表示支持的域,即哪些來(lái)源的域允許訪問(wèn)。
- maxAge:表示預(yù)檢信息的有效緩存時(shí)間,單位是秒
- allowedHeaders:表示允許的請(qǐng)求頭。
@GetMapping("/getMsg")@CrossOrigin(value = "http://localhost:8081")public String getMsg(){return "GET success";}@DeleteMapping("/delMsg")@CrossOrigin(value = "http://localhost:8081")public String delMsg(){return "delete success";}
新建一個(gè)新的web項(xiàng)目(換個(gè)端口啟動(dòng))發(fā)起ajax跨域請(qǐng)求。
<script src="/jquery-1.8.3.min.js"></script><body>
<button onclick="sendAjax()">點(diǎn)擊發(fā)送ajax請(qǐng)求</button>
</body><script>function sendAjax() {$.ajax({url:"http://localhost/getMsg",type:"get",success:function (result) {alert(result)}})}
</script>
2.基于過(guò)濾器的實(shí)現(xiàn)方案
@Configuration
public class CorsFilterConfig {@Beanpublic FilterRegistrationBean<CorsFilter> corsFilter(){FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean=new FilterRegistrationBean<>();UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();CorsConfiguration corsConfiguration=new CorsConfiguration();corsConfiguration.addAllowedHeader("*");//允許的請(qǐng)求頭
// corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedOriginPattern("*");//允許的origin域名corsConfiguration.setAllowCredentials(true); //是否允許發(fā)cookiecorsConfiguration.setMaxAge(3600L);//從預(yù)檢請(qǐng)求得到相應(yīng)的最大時(shí)間,默認(rèn)30分鐘corsConfiguration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT")); //允許的請(qǐng)求方法source.registerCorsConfiguration("/**",corsConfiguration);//指定可以跨域的路徑corsFilterFilterRegistrationBean.setFilter(new CorsFilter(source));corsFilterFilterRegistrationBean.setOrder(-1);return corsFilterFilterRegistrationBean;}
}
統(tǒng)一響應(yīng)數(shù)據(jù)格式
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseData<T> {private String code;//響應(yīng)狀態(tài)碼private String errorMsg;//用于封裝異常信息,正常返回一般為null即可private Boolean result;//表示執(zhí)行成功還是失敗private T data;//封裝返回?cái)?shù)據(jù)
}
Spring Boot 異常處理
自定義錯(cuò)誤頁(yè)
如果不需要向用戶展示錯(cuò)誤的詳細(xì)信息,可以把錯(cuò)誤信息定義成靜態(tài)頁(yè)面,簡(jiǎn)單地輸出自定義的出錯(cuò)啦或找不到之類的網(wǎng)頁(yè)。 在靜態(tài)文件路徑下創(chuàng)建 error 目錄并創(chuàng)建 4xx.html 或 5xx.html 頁(yè)面,則發(fā)生 4 開頭的錯(cuò)誤狀態(tài)碼代表的異常時(shí)將返回 4xx.html,當(dāng)發(fā)生 5 開頭的錯(cuò)誤狀態(tài)碼代表的異常時(shí)將返回5xx.html。還可以用更具體的錯(cuò)誤狀態(tài)碼命名的文件,如 404.html,則發(fā)生 404 錯(cuò)誤時(shí)則會(huì)直接返回,當(dāng)發(fā)生 403 等錯(cuò)誤時(shí)返回 4xx。如果最后都找到不到的話還會(huì)返回springboot 自帶的默認(rèn)白頁(yè)。
@ControllerAdvice 全局統(tǒng)一異常處理
如果客戶端需要比較具體的異常信息,則不能用上述簡(jiǎn)單方法,一般要用注解@ControllerAdvice 進(jìn)行統(tǒng)一異常處理,如果返回 json 格式的數(shù)據(jù)也可以使用@RestControllerAdvice,只需要?jiǎng)?chuàng)建一個(gè)類加上這個(gè)注解就可以捕捉到異常,然后類中各個(gè)方法再用@ExceptionHandler 注解來(lái)對(duì)具體的各個(gè)異常分別進(jìn)行處理
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(NullPointerException.class)public ResponseData exception(NullPointerException exception) {return new ResponseData("500", "空指針異常",false, null);}@ExceptionHandler(IndexOutOfBoundsException.class)public ResponseData exception(IndexOutOfBoundsException exception) {return new ResponseData("500", "數(shù)組越界異常", false,null);}@ExceptionHandler(Exception.class)public ResponseData exception(Exception exception) {return new ResponseData("500", exception.getMessage(),false, null);}}
測(cè)試類
@RequestMapping("/exception")
@RestController
public class ExceptionController {@GetMapping("/test1")public ResponseData test1() {UserInfo userInfo = null;userInfo.setUsername("zhangsan");return new ResponseData("200",null,true,userInfo);}@GetMapping("/test2")public ResponseData test2() {int[] arr= {1,2,3};System.out.println(arr[3]);//發(fā)生越界針異常//以下是正常業(yè)務(wù)代碼 省略return new ResponseData("200",null,true,arr);}@GetMapping("/test3")public ResponseData test3() {int i=10/0; //發(fā)生算術(shù)異常//以下是正常業(yè)務(wù)代碼return new ResponseData("200",null,true,i);}}
文件上傳
單文件上傳
Spring Boot 提供了自動(dòng)配置類 MultipartAutoConfigure 可以實(shí)現(xiàn)文件上傳,只需導(dǎo)入 spring-boot-starter-web 以及配置 spring.servlet.multipart.enabled=true 即可生效。
#表示是否開啟文件上傳支持,默認(rèn)為true
spring.servlet.multipart.enabled=true
#修改文件上傳臨時(shí)保存路徑
spring.servlet.multipart.location=C:/temp
#單個(gè)上傳文件的最大限制 默認(rèn)是1M
spring.servlet.multipart.max-file-size=2MB
#多個(gè)上傳文件的最大限制 默認(rèn)是10M
spring.servlet.multipart.max-request-size=10MB
#文件寫入磁盤的閾值
spring.servlet.multipart.file-size-threshold=0B
@RestController
@RequestMapping("/upload")
public class FileUploadController {@PostMappingpublic ResponseData upload(MultipartFile file , HttpServletRequest request){if (!file.isEmpty()) {//默認(rèn)是上傳到項(xiàng)目的webapp下String realPath = request.getServletContext().getRealPath("/uploadFile");File savePath= new File(realPath);if (!savePath.exists()) {savePath.mkdirs();}String fileName= UUID.randomUUID().toString().replace("-","");String originalFilename = file.getOriginalFilename();String suffix = originalFilename.substring(originalFilename.indexOf("."));File saveFile= new File(savePath,fileName+suffix);try {file.transferTo(saveFile);return new ResponseData("200","上傳成功",true,null);} catch (IOException e) {return new ResponseData("500","上傳出現(xiàn)異常",false,null);}}else{return new ResponseData("500","文件必傳",false,null);}}
}
多文件上傳
Thymeleaf 視圖層技術(shù)
使用過(guò)程
1.加依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.配置thymeleaf模板視圖解析器
在application. properties中可以添加關(guān)于Thymeleaf模板視圖解釋器的配置項(xiàng),也可以不添加,使用默認(rèn)值。參考代碼如下:
#關(guān)閉Thymeleaf緩存,這樣開發(fā)時(shí)方便測(cè)試,無(wú)須重啟
spring.thymeleaf.cache=false
#設(shè)置Thymeleaf頁(yè)面編碼
spring.thymeleaf.encoding=utf-8
#Thymeleaf模式
spring.thymeleaf.mode=HTML5
#Thymeleaf頁(yè)面的后綴
spring.thymeleaf.suffix=.html
#Thymeleaf頁(yè)面的存儲(chǔ)路徑(前綴)
spring.thymeleaf.prefix=classpath:/templates/
3.頁(yè)面引入命名空間
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>hello</title>
</head>
<body>
歡迎用戶<span th:text="${username}">hello</span>登錄
</body>
</html>
4.創(chuàng)建控制器
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {@GetMapping("/index")public String index(Model model){model.addAttribute("username","jf3q");return "hello";}
}
基礎(chǔ)語(yǔ)法
1.th:text:文本的賦值與替換
<div th:text="${text1}">將被替換掉的原始值</div>
如果替換的文本中有html代碼的話,瀏覽器不能識(shí)別
<div th:text="${text2}">不能識(shí)別文本中的HTML標(biāo)簽</div>
控制器中加的代碼
model.addAttribute("text2","<h1>hello world</h1>");
2.th:utext
跟th:text用法一樣,不同的是如果文本中包含 HTML 標(biāo)簽,瀏覽器可以識(shí)別。
<div th:utext="${text2}">能識(shí)別文本中的HTML標(biāo)簽</div>
3.th:value
給有 value 屬性的 HTML 標(biāo)簽賦值
用戶名:<input type="text" th:value="${username}" /><br/>
4.th:checked
用于決定單選或復(fù)選框是否選中
性別:<input type="radio" th:checked="${gender}=='男'" />男
<input type="radio" th:checked="${gender}=='女'" />女<br/>
5.th:selected
決定下拉選擇框中的選項(xiàng)是否被選中
城市<select><option th:selected="${city}=='北京'">北京</option><option th:selected="${city}=='上海'">上海</option><option th:selected="${city}=='廣州'">廣州</option><option th:selected="${city}=='深圳'">深圳</option>
</select>
控制器中加city值
model.addAttribute("city","廣州");
6.th:each
用來(lái)遍歷集合
User user1=new User(1,"李白","123");
User user2=new User(2,"杜甫","123");
List<User> users=new ArrayList<>();
users.add(user1);
users.add(user2);
model.addAttribute("users",users);
用戶列表如下:
<table border="1"><tr><th>編號(hào)</th><th>用戶名</th><th>密碼</th></tr><tr th:each="user:${users}"><td th:text="${user.id}"></td><td th:text="${user.username}"></td><td th:text="${user.password}"></td></tr>
</table>
除了遍歷元素,還可于獲取遍歷的狀態(tài),thymeleaf 提供如下狀態(tài):
- index:當(dāng)前的遍歷索引,從 0 開始
- count:當(dāng)前的遍歷索引,從 1 開始
- size:被遍歷變量里的元素?cái)?shù)量。
- current:每次遍歷的遍歷變量。
- even:當(dāng)前的遍歷是否為偶數(shù)次。
- odd:當(dāng)前的遍歷是否為奇數(shù)次
- first:當(dāng)前是否為首次遍歷。
- last: 當(dāng)前是否為最后一次遍歷。
用戶列表(含狀態(tài))如下:
<table border="1"><tr><th>編號(hào)</th><th>用戶名</th><th>密碼</th><th>索引號(hào)</th><th>是否第一個(gè)</th><th>是否最后一個(gè)</th><th>是否偶數(shù)次</th></tr><tr th:each="user,state:${users}"><td th:text="${user.id}"></td><td th:text="${user.username}"></td><td th:text="${user.password}"></td><td th:text="${state.index}"></td><td th:text="${state.first}"></td><td th:text="${state.last}"></td><td th:text="${state.even}"></td></tr>
</table>
7.th:if
選擇結(jié)構(gòu),控制數(shù)據(jù)是否在頁(yè)面上顯示,當(dāng)條件為 true 時(shí)將填充數(shù)據(jù)到閉合標(biāo)簽內(nèi)部
<div th:if="${username}==jf3q" th:text="該用戶是管理員"></div>
8.th:unless
選擇結(jié)構(gòu),當(dāng)條件為 false 時(shí)將填充數(shù)據(jù)到閉合標(biāo)簽內(nèi)部
<div th:unless="${username}==jf3q" th:text="該用戶是普通用戶"></div>
9.th:swith 與 th:case
多重選擇分支結(jié)構(gòu),
<div th:switch="${city}"><div th:case="北京">北京</div><div th:case="上海">上海</div><div th:case="廣州">廣州</div><div th:case="深圳">深圳</div><div th:case="">不確定</div>
</div>
10.th:attr
11.th:class 與 th:style
spel表達(dá)式
Thymeleaf 提供了 KaTeX parse error: Expected 'EOF', got '#' at position 8: {}、*{}、#?{}、@{}四種占位符,在{}…{}
用于獲取 Model 中的字符串或?qū)ο?#xff0c;如果是對(duì)象還可以用點(diǎn)運(yùn)算符進(jìn)一步獲取對(duì)象的 屬性值或方法??梢垣@取 Servlet 的各種內(nèi)置對(duì)象,也可以獲取 Thymeleaf 的內(nèi)置對(duì)象,如 dates,numbers,strings,arrays,lists 等等。
2.{}
其中的號(hào)代表一個(gè)對(duì)象,大括號(hào)里面的內(nèi)容代表對(duì)象的屬性,通常要結(jié)合 th:object 屬性一起使用,th:object 用來(lái)獲取一個(gè)對(duì)象,然后再用*{}去獲取對(duì)象的各個(gè)屬性值。
3.#{}
用于讀取取國(guó)際化 properties 文件的屬性。
4.@{}
Thymeleaf 表達(dá)式
Thymeaf 除了使用 SpEL 表達(dá)式外,還有自己的表達(dá)式,在${}的大括號(hào)中使用的表達(dá)式屬于 SpEL 表達(dá)式,而在 th:屬性=""的雙引號(hào)中應(yīng)用的是 Thymeleaf 自身的表達(dá)式。
1.比較運(yùn)算
可以使用的運(yùn)算符包括>、>=、 、 != 、< 、<= ,其中的>和<本身是 HTML 標(biāo)簽的關(guān)鍵字,為了避免歧義,可使用別名,gt 對(duì)應(yīng)>,lt 對(duì)應(yīng)<,ge 對(duì)應(yīng)>=,le 對(duì)應(yīng)<=,not 對(duì)應(yīng)!,eq 對(duì)應(yīng),neq 或 nq 對(duì)應(yīng)!=。
2.三目運(yùn)算
3.邏輯運(yùn)算
是否登錄:<span th:text="${username=='admin'&&password=='123'}"></span>
內(nèi)置對(duì)象
在 Thymeleaf 中的內(nèi)置對(duì)象有:
- #ctx:上下文對(duì)象。
- #request:獲取 HttpServletRequest 對(duì)象。
- #response:獲取 HttpServletResponse 對(duì)象。
- #session:獲取 HttpSession 對(duì)象
- #servletContext:獲取 HttpServletContext 對(duì)象
- #dates:日期格式化內(nèi)置對(duì)象,具體方法可以參照 java.util.Date
- #calendars:類似于#dates,但是 java.util.Calendar 類的方法;
- #numbers:數(shù)字格式化;
- #strings:字符串格式化,具體方法可以參照 java.lang.String,如 startsWith、contains 等;
- #objects:參照 java.lang.Object
- #bools:判斷 boolean 類型的工具
- #arrays:數(shù)組操作的工具
- #lists:列表操作的工具,參照 java.util.List
- #sets:Set 集合操作工具,參照 java.util.Set
- #maps:Map 集合操作工具,參照 java.util.Map
- #aggregates:操作數(shù)組或集合創(chuàng)建聚合的工具
- #messages
測(cè)試
模板片段
系統(tǒng)中的很多頁(yè)面有很多公共內(nèi)容,例如標(biāo)題欄、主菜單、側(cè)邊欄、頁(yè)腳等,這些公共內(nèi)容可以提取放在一個(gè)稱為“模板片段”的公共頁(yè)面里面,其它頁(yè)面可以引用這個(gè)“模板片段”內(nèi)容。
1.模板片段的定義
普通 html 標(biāo)簽或 標(biāo)簽,添加 th:fragment 屬性,這樣這個(gè)標(biāo)簽及其內(nèi)部的所有內(nèi)容就定義為一個(gè)模板片段。語(yǔ)法是 th:fragment=“模板片段名稱”。
這里,表示將 block 標(biāo)簽定義為一個(gè)模板片段,模板片段的名稱叫 loginForm,定義了模板片段的當(dāng)前 HTML 文件就稱為模板,模板名稱就是 HTML 文檔的名字(不含后綴),此處模板名稱為 login。
2.引用片段
1)插入整個(gè)模板
使用 th:insert 屬性插入整個(gè)模板。 語(yǔ)法:th:insert=“~{模板名稱}” 除此之外,還可以使用 th:replace 和 th:include 插入。
2)插入模板片段
語(yǔ)法:th:insert=“~{模板名稱::模板片斷名稱}” 插入模板中的其中一個(gè)指定名稱的片斷,模板片斷名可以對(duì)應(yīng) th:fragment 定義的名稱,也可以用類似 JQuery 選擇器的語(yǔ)法選擇部分片段。
3)th:insert、th:replace、th:include 的區(qū)別
- th:insert:將公共片段整個(gè)插入到聲明引入的元素中
- th:replace:將聲明引入的元素替換為公共片段
- th:include:將被引入的片段的內(nèi)容包含進(jìn)這個(gè)標(biāo)簽中
3.模板片段傳入?yún)?shù)
帶參數(shù)的模板片段定義語(yǔ)法:th:fragment=“模板片段名稱(參數(shù)列表)”。參數(shù)列表指可以是一個(gè)或多個(gè)參數(shù)。并且在模板片段內(nèi)部需要內(nèi)容不同的位置使用參數(shù),使用方式: 參數(shù)名稱,例如: < s p a n t h : t e x t = " {參數(shù)名稱},例如:<span th:text=" 參數(shù)名稱,例如:<spanth:text="{參數(shù)}" >。
引用語(yǔ)法:~{模板名稱::模板片斷名稱(參數(shù)列表)}。這個(gè)參數(shù)列表是有實(shí)際值的。
綜合實(shí)例
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {private Integer id;private String name;private String gender;private Integer age;private String classname;}
List<Student> students= new ArrayList<>();students.add(new Student(1, "張三","女",20, "計(jì)科1班"));students.add(new Student(2, "李四","男",21, "計(jì)科2班"));students.add(new Student(3, "李白","男",18, "計(jì)科3班"));model.addAttribute("students",students);return "students";
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>學(xué)生列表</title>
</head>
<body><table><tr><td>id</td><td>姓名</td><td>性別</td><td>年齡</td><td>班級(jí)</td></tr><tr th:each="s:${students}"><td th:text="${s.id}"></td><td th:text="${s.name}"></td><td><input type="radio" th:checked="${s.gender}=='男'" />男<input type="radio" th:checked="${s.gender}=='女'" />女</td><td th:text="${s.age}"></td><td><select ><option th:selected="${s.classname}=='計(jì)科1班'">計(jì)科1班</option><option th:selected="${s.classname}=='計(jì)科2班'">計(jì)科2班</option><option th:selected="${s.classname}=='計(jì)科3班'">計(jì)科3班</option></select></td></tr>
</table></body>
</html>
接口文檔 Swagger3.0
Swagger 是一個(gè)用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)框架,最主 要的組件是 Swagger UI,該組件提供了一個(gè)可視化的 UI 頁(yè)面展示描述文件,可以在該頁(yè)面 中對(duì)相關(guān)接口進(jìn)行查閱或做一些簡(jiǎn)單的接口請(qǐng)求。Swagger3.0 和之前版本的依賴不太一樣
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
常用注解
- @API:用于類上,表示標(biāo)識(shí)這個(gè)類是 swagger 的資源(tags,value,hidden)
- @ApiOperation:用于方法上,表示一個(gè) http 請(qǐng)求的動(dòng)作(value,notes,httpMethod, hidden)
- @ApiParam:用于方法,參數(shù)或字段說(shuō)明,表示對(duì)參數(shù)的添加元數(shù)據(jù),說(shuō)明或是否 必填等(name,value,required)
- @ApiModel:用于類上,表示對(duì)類進(jìn)行說(shuō)明,用于參數(shù)用實(shí)體類接收(value, description)
- @ApiModelProperty:用于方法或字段,表示對(duì) model 屬性的說(shuō)明或者數(shù)據(jù)操作更改 (value,name,dataType,required,example,hidden)
- @ApiIgnore:用于類,方法或方法參數(shù)上,表示這個(gè)類,或者方法或者參數(shù)被忽略 (value)
- @ApiResponses:用于方法上,方法返回對(duì)象的說(shuō)明(多個(gè) @ApiResponse)
- @ApiResponse:用于方法上,每個(gè)參數(shù)的說(shuō)明(code,message,response)
- @ApiImplicitParams:用于方法上,包含一組參數(shù)說(shuō)明(多個(gè) @ApiImplicitParam)
- @ApiImplicitParam :用于方法上,表示單獨(dú)的請(qǐng)求參數(shù)(name,value,required,paramType,dataType,readOnly,allowEmptyValue,defaultValue
springboot整合swagger流程
由于spring Boot 3.0 在寫稿時(shí)仍然處于快速迭代中,對(duì) swagger3.0 的支持不太好,故這里暫時(shí)退到最近一個(gè)穩(wěn)定版本 spring boot2.7.1 來(lái)講解 Spring Boot 整合 Swagger3。
1.加依賴
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
2.Application.properties 中添加如下配置:
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
這個(gè)配置的作用是將 SpringBoot 路徑匹配模式修改為 AntPathMatcher。Spring Boot 2.6.0 開始使用基于 PathPatternParser 的路徑匹配,而 Springfox 版本一直沒(méi)有更新還是使用 的 AntPathMatcher,如果不這樣配置,將會(huì)拋出以下異常:
3.創(chuàng)建實(shí)體類 User
@Data
@AllArgsConstructor
@ApiModel(value = "用戶User類",description = "描述用戶User信息")
public class UserInfo {@ApiModelProperty(value = "用戶id")private Integer id;@ApiModelProperty(value = "用戶名")private String username;@ApiModelProperty(value = "密碼")private String password;
}
4.創(chuàng)建配置類 SwaggerConfig 啟用 Swagger
@Configuration
@EnableOpenApi
public class SwaggerConfig {@Beanpublic Docket desertsApi(){return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.example.swagger_demo.controller"))//按包掃描,.paths(PathSelectors.any()).build().groupName("jf3q").enable(true);}private ApiInfo apiInfo(){return new ApiInfoBuilder().title("用戶管理系統(tǒng)說(shuō)明API文檔")//標(biāo)題.description("用戶管理系統(tǒng)說(shuō)明API文檔")//描述.contact(new Contact("jfit", "https://www.jf3q.com", "12345@qq.com"))//作者信息
// .termsOfServiceUrl("https://www.sike.com").version("1.0")//版本號(hào).build();}
}
5.controller
@RestController
@RequestMapping("/user")
@Api(tags = "User操作接口")
public class UserInfoController {@AutowiredUserInfoService userInfoService;@GetMapping("/{id}")@ApiOperation(value = "根據(jù)id查找用戶對(duì)象", notes = "根據(jù)id查找用戶對(duì)象")public ResultVo<UserInfo> getUser(@ApiParam(value = "用戶ID", example = "1", required = true)@PathVariable Integer id){UserInfo userInfo= userInfoService.getUser(id);return ResultVo.success("",userInfo);}@GetMapping@ApiOperation(value = "獲取所有用戶對(duì)象", notes = "獲取所有用戶,無(wú)需參數(shù)")public ResultVo<List<UserInfo>> getList(){List<UserInfo> list=userInfoService.getList();return ResultVo.success("",list);}
}
6.訪問(wèn)接口文檔頁(yè)面
http://localhost:端口/swagger-ui/index.html
美化ui界面
Swagger 自帶的 UI 界面不是很好看,可以使用流行的第三方 swagger-bootstrap-ui 進(jìn)行 美化,添加如下依賴,重新啟動(dòng),訪問(wèn)地址:http://localhost:端口/doc.html
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version>
</dependency>
生產(chǎn)環(huán)境關(guān)閉swagger
一般 Swagger 只在開發(fā)和測(cè)試環(huán)境中使用,不帶到生產(chǎn)環(huán)境中去??梢酝ㄟ^(guò)修改配置類 SwaggerConfig 里面的代碼 enable(true)為 enable(false)來(lái)快速關(guān)閉 Swagger。更好的辦法是自動(dòng)識(shí)別是生成環(huán)境還是開發(fā)或測(cè)試環(huán)境,自動(dòng)關(guān)閉或開啟
@Bean
public Docket desertsApi(Environment environment){//開發(fā)環(huán)境和測(cè)試環(huán)境
Profiles profiles=Profiles.of("dev","test");
//判斷是否處在自己設(shè)定的環(huán)境當(dāng)中
boolean swaggerEnabled = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swagger_demo.controller"))//按包掃描,
.paths(PathSelectors.any())
.build()
.groupName("jf3q")
.enable(swaggerEnabled);
}
作業(yè)
1.把掌上游戲app項(xiàng)目改成springboot項(xiàng)目(mybatis部分先不用動(dòng)),并集成swagger生成在線接口文檔(已經(jīng)就包含了本章所有內(nèi)容)
2.練習(xí)thymeleaf小案例