Spring boot之WEB 開發(fā)-靜態(tài)資源訪問
官方文檔
在線文檔:
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.develo\ping-web-applications
基本介紹
1. 只要靜態(tài)資源放在類路徑下: /static 、/public 、/resources 、/META-INF/resources可以被直接訪問- 對應文件WebProperties.java
private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
{ "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
2. 常見靜態(tài)資源:JS、CSS 、圖片(.jpg .png .gif .bmp .svg)、字體文件(Fonts)等
3. 訪問方式:默認: 項目根路徑/ + 靜態(tài)資源名比如http://localhost:8080/hi.jpg . - 設置WebMvcProperties.java
private String staticPathPattern = “/**”;
快速入門
1. 創(chuàng)建SpringBoot 項目springbootweb , 使用靈活配置方式來創(chuàng)建項目
2. 創(chuàng)建相關靜態(tài)資源目錄, 并放入測試圖片, 沒有目錄,自己創(chuàng)建即可, 完成測試
靜態(tài)資源訪問注意事項和細節(jié)
1. 靜態(tài)資源訪問原理:靜態(tài)映射是, 也就是對所有請求攔截,請求進來,先看Controller
能不能處理,不能處理的請求交給靜態(tài)資源處理器,如果靜態(tài)資源找不到則響應404 頁面
2. 改變靜態(tài)資源訪問前綴,比如我們希望http://localhost:8080/hellores/* 去請求靜態(tài)資源
應用場景:靜態(tài)資源訪問前綴和控制器請求路徑沖突
1) 創(chuàng)建application.yml
spring:
mvc:
static-path-pattern: /hellores/**
2) 重啟應用,完成測試, 瀏覽器輸入: http://localhost:8080/hellores/1.jpg
3.改變默認的靜態(tài)資源路徑,比如希望在類路徑下增加ninhaoimg 目錄作為靜態(tài)資源路徑
并完成測試.
spring:
mvc:
static-path-pattern: /hellores/** #修改靜態(tài)資源訪問的路徑/前綴
web:
resources:
#修改/指定 靜態(tài)資源的訪問路徑/位置
#
static-locations: ["classpath:/ninhaoimg/","classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"] #String[] staticLocations
3) 測試, 瀏覽器輸入http://localhost:8080/hellores/pen.jpg
[提示: 沒錯就是這樣訪問pen.jpg, 不是/ninhaoimg /pen.jpg 形式, 另外因為pen.jpg 還是拷貝來的, 一定要保證工作目錄target 有pen.jpg ,如果沒有, 請rebulid 下項目, 再重啟項目]
4) 如果你配置static-locations, 原來的訪問路徑就被覆蓋,如果需要保留,你再指定一下即可
spring:
mvc:
static-path-pattern: /hellores/** #修改靜態(tài)資源訪問的路徑/前綴
web:
resources:
#修改/指定靜態(tài)資源的訪問路徑/位置
static-locations: ["classpath:/ninhaoimg /","classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"]
#String[] staticLocations
這之所以不需要http://localhost:8080/hellores/ninhaoimg/12.jpg
是因為修改的默認訪問路勁 容器在其他目錄找不到的時候就會默認去找ninhaoimg目錄下的12.jap
自定義轉換器
基本介紹
1. SpringBoot 在響應客戶端請求時,將提交的數(shù)據封裝成對象時,使用了內置的轉換器
2. SpringBoot 也支持自定義轉換器, 這個內置轉換器在debug 的時候, 可以看到, 后面給演示, 提供了124 個內置轉換器. 看下源碼GenericConverter-ConvertiblePair
自定義轉換器-應用實例
需求說明: 演示自定義轉換器使用
代碼實現(xiàn)
修改save.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加妖怪</title>
</head>
<body>
<h1>添加妖怪-坐騎[測試封裝POJO;]</h1>
<form action="/savemonster" method="post">
編號: <input name="id" value="100"><br/>
姓名: <input name="name" value="牛魔王"/> <br/>
年齡: <input name="age" value="500"/> <br/>
婚否: <input name="isMarried" value="true"/> <br/>
生日: <input name="birth" value="2000/11/11"/> <br/>
<!-- 使用自定義轉換器關聯(lián)car, 字符串整體提交, 使用,號間隔 -->
坐騎:<input name="car" value="避水金晶獸,666.6"><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>
創(chuàng)建WebConfig.java,增加自定義轉換器
/**
* @Configuration(proxyBeanMethods = false)
* 1. 表示 WebConfig 是一個配置類
* 2. proxyBeanMethods = false 使用Lite模式
*/
@Configuration(proxyBeanMethods = false)
public class WebConfig {
//注入bean WebMvcConfigurer
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
/**
* 解讀
* 1. 在addFormatters 方法中,增加一個自定義的轉換器
* 2. 增加自定義轉換器 String -> Car
* 3. 增加的自定義轉換器會注冊到 converters 容器中
* 4. converters 底層結構是 ConcurrentHashMap 內置有124轉換器
* 5. 一會會使用debug來看到這些轉換器
*/
registry.addConverter(new Converter<String, Car>() {
@Override
public Car convert(String source) {//source就是 傳入的字符串 避水金晶獸,666.6
//這里就加入你的自定義的轉換業(yè)務代碼
if (!ObjectUtils.isEmpty(source)) {
Car car = new Car();
String[] split = source.split(",");
car.setName(split[0]);
car.setPrice(Double.parseDouble(split[1]));
return car;
}
return null;
}
});
//轉種寫法來注冊自定義轉換器-方便理解
1.先創(chuàng)建自定義的轉換器
//Converter<String,Car> hspConverter = new Converter<String, Car>() {
// @Override
// public Car convert(String source) {//source就是 傳入的字符串 避水金晶獸,666.6
// //這里就加入你的自定義的轉換業(yè)務代碼
// if (!ObjectUtils.isEmpty(source)) {
//
// Car car = new Car();
// String[] split = source.split(",");
// car.setName(split[0]);
// car.setPrice(Double.parseDouble(split[1]));
// return car;
// }
// return null;
// }
//};
//
還可以增加更多的轉換器
//
第2個自定義轉換器
//Converter<String,Monster> hspConverter2 = new Converter<String, Monster>() {
// @Override
// public Monster convert(String source) {//source就是 傳入的字符串 避水金晶獸,666.6
// return null;
// }
//};
//
第3個自定義轉換器
//Converter<String,Car> hspConverter3 = new Converter<String, Car>() {
// @Override
// public Car convert(String source) {//source就是 傳入的字符串 避水金晶獸,666.6
// System.out.println("source-" + source);
// return null;
// }
//};
//
2添加轉換器到converters key-[源類型->目標類型]
//registry.addConverter(hspConverter);
//registry.addConverter(hspConverter2);
//registry.addConverter(hspConverter3);
}
};
}
}
3. 完成測試, 瀏覽器http://localhost:8080/save.html
4. Debug 可以看到我們新增的Converter
------注意看, 多了一個我們自定義的轉換器String->com.wyxedu.web.bean.Car
處理JSON
需求說明:
演示返回JSON 格式數(shù)據
應用實例
1. SpringBoot 支持返回JSON 格式數(shù)據,在啟用WEB 開發(fā)場景時,已經引入了相關依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
創(chuàng)建ResponseController.java
@Controller
public class ResponseController {
//返回Monster數(shù)據-要求以json格式返回
@GetMapping("/get/monster")
@ResponseBody
public Monster getMonster() {
//說明
//開發(fā)中, monster對象是從DB獲取-這里模擬一個monster對象
Monster monster = new Monster();
monster.setId(100);
monster.setName("奔波霸");
monster.setAge(200);
monster.setIsMarried(false);
monster.setBirth(new Date());
Car car = new Car();
car.setName("奔馳");
car.setPrice(222.2);
monster.setCar(car);
return monster;
}
}
Postman 完成測試
Debug 一下monster 對象以Json 格式返回
內容協(xié)商
基本介紹
1. 根據客戶端接收能力不同,SpringBoot 返回不同媒體類型的數(shù)據
2. 比如: 客戶端Http 請求Accept: application/xml 則返回xml 數(shù)據,客戶端Http 請求Accept: application/json 則返回json 數(shù)據
比如下面的示意圖
內容協(xié)商-應用實例
● 需求說明: 使用Postman 發(fā)送Http 請求,根據請求頭不同,返回對應的json 數(shù)據或者xml
數(shù)據, 如圖
在pom.xml 增加處理xml 的依賴
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
2. 使用Postman 發(fā)出不同的Http Header , 可以看到返回對應的數(shù)據格式(說明: 測試前請重啟一把項目)
3. 切換Postman 不同的Accept 類型, 來Debug 源碼, 看看對應的JsonGenerator 類型
4. 使用瀏覽器請求,為什么會返回xml 數(shù)據分析,而不是json?
注意事項和使用細節(jié)
1. Postman 可以通過修改Accept 的值,來返回不同的數(shù)據格式
2. 對于瀏覽器,我們無法修改其Accept 的值,怎么辦? 解決方案: 開啟支持基于請求參數(shù)的內容協(xié)商功能
1) 修改application.yml, 開啟基于請求參數(shù)的內容協(xié)商功能
spring:
mvc:
#static-path-pattern: /hellores/** #修改靜態(tài)資源訪問的路徑/前綴
hiddenmethod:
filter:
enabled: true #啟用了HiddenHttpMethodFilter,開啟頁面表單的Rest功能
view: #配置視圖解析器
suffix: .html
prefix: / #這里是需要注意 prefix需要和當前的static-path-pattern一致
contentnegotiation:
favor-parameter: true #開啟基于請求參數(shù)的內容協(xié)商功能
web:
resources:
#修改/指定 靜態(tài)資源的訪問路徑/位置
#
static-locations: ["classpath:/ninhaoimg/","classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"] #String[] staticLocations
2)完成測試
- 注意,參數(shù)format 是規(guī)定好的, 在開啟請求參數(shù)的內容協(xié)商功能后,SpringBoot 底層ParameterContentNegotiationStrategy 會通過format 來接收參數(shù),然后返回對應的媒體類型/
數(shù)據格式, 當然format=xx 這個xx 媒體類型/數(shù)據格式是SpringBoot 可以處理的才行,不能亂寫.
如果需要自定義format 在配置文件加一個
parameter-name: wwwformat #指定一個內容協(xié)商的參數(shù)名 就好了然后要指定上面格式就不是format=json 而是 wwwformat=json文章來源:http://www.zghlxwxcb.cn/news/detail-486179.html
spring:
mvc:
#static-path-pattern: /hellores/** #修改靜態(tài)資源訪問的路徑/前綴
hiddenmethod:
filter:
enabled: true #啟用了HiddenHttpMethodFilter,開啟頁面表單的Rest功能
view: #配置視圖解析器
suffix: .html
prefix: / #這里是需要注意 prefix需要和當前的static-path-pattern一致
contentnegotiation:
favor-parameter: true #開啟基于請求參數(shù)的內容協(xié)商功能
parameter-name: wwwformat #指定一個內容協(xié)商的參數(shù)名
web:
resources:
#修改/指定 靜態(tài)資源的訪問路徑/位置
#
static-locations: ["classpath:/ninhaoimg/","classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"] #String[] staticLocations
.l…文章來源地址http://www.zghlxwxcb.cn/news/detail-486179.html
到了這里,關于Spring boot之WEB 開發(fā)-靜態(tài)資源訪問--自定義轉換器--處理JSON--內容協(xié)商的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!