文章目錄
- WEB開發-靜態資源訪問
- 官方文檔
- 基本介紹
- 快速入門
- 注意事項和細節
- Rest風格請求處理
- 基本介紹
- 應用實例
- 注意事項和細節
- 思考題
- 接收參數相關注解
- 基本介紹
- 應用實例
- @PathVariable
- @RequestHeader
- @RequestParam
- @CookieValue
- @RequestBody
- @RequestAttribute
- @SessionAttribute
?? 上一篇: springboot系列七: Lombok注解,Spring Initializr,yaml語法
🎉 歡迎來到 springboot系列八: springboot靜態資源訪問,Rest風格請求處理, 接收參數相關注解 🎉
在本篇文章中,我們將探討如何在 Spring Boot 中處理靜態資源訪問、實現 Rest 風格的請求處理以及使用接收參數相關的注解。這些功能將幫助您更高效地開發和管理 Spring Boot 應用程序。
🔧 本篇需要用到的項目:
WEB開發-靜態資源訪問
官方文檔
在線文檔:
基本介紹
1.只要靜態資源放在類路徑下: /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.常見靜態資源: JS, CSS, 圖片(.jpg, .png, .gif, .bmp, .svg), 字體文件(Fonts)等
3.訪問方式: 默認: 項目根路徑 / + 靜態資源名, 比如 http://localhost:8080/1.jpg - 設置WebMvcProperties.java
private String staticPathPattern = “/**”;
快速入門
1.創建SpringBoot
項目springbootweb
, 這里使用靈活配置方式來創建項目, 參考springboot快速入門
2.創建相關靜態資源目錄, 并放入測試圖片, 沒有目錄, 自己創建即可
, 瀏覽器訪問 http://localhost:8080/4.png , 完成測試.
注意事項和細節
1.靜態資源訪問原理: 靜態映射是 /** , 也就是對所有請求攔截. 請求進來, 先看Controller能不能處理, 不能處理的請求交給靜態資源處理器, 如果靜態資源找不到則響應404頁面.
2.改變靜態資源訪問前綴, 比如我們希望 http://localhost:8080/image/1.png 去請求靜態資源.
應用場景: http://localhost:8080/1.png, 靜態資源訪問前綴和控制器請求路徑沖突
被Controller攔截
解決方案:
1)創建src/main/resources/application.yml
spring:mvc:static-path-pattern: /image/**
2)啟動, http://localhost:8080/image/1.png 測試
3.改變默認的靜態資源路徑, 比如希望在類路徑下增加zzwimg
目錄 作為靜態資源路徑, 并完成測試.
1)如圖所示
2)配置 application.yml
, 增加路徑
spring:mvc:static-path-pattern: /image/** #修改靜態資源訪問 路徑/前綴web:resources:#修改/指定 靜態資源的訪問路徑/位置static-locations: [classpath:/zzwimg/] #String[] staticLocations
3)測試, 瀏覽器輸入 http://localhost:8080/image/6.png
(沒錯, 是image/6.png
, 不是image/zzwimg/6.png
), 一定要保證工作目錄target
下 有 6.png
, 如果沒有, 請rebuild
下項目, 再重啟項目.
4)如果你配置 static-locations
, 原來的訪問路徑就會被覆蓋, 如果需要保留, 再指定一下即可.
web:resources:#修改/指定 靜態資源的訪問路徑/位置 String[] staticLocationsstatic-locations: ["classpath:/zzwimg/", "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"]
Rest風格請求處理
基本介紹
1.Rest
風格支持 (使用HTTP
請求方式來表示對資源的操作)
2.舉例說明
請求方式: /monster
GET-獲取妖怪
DELETE-刪除妖怪
PUT-修改妖怪
POST-保存妖怪
應用實例
1.創建src/main/java/com/zzw/springboot/controller/MonsterController.java
@RestController
public class MonsterController {//等價的寫法//@RequestMapping(value = "/monster", method= RequestMethod.GET)@GetMapping("/monster")public String getMonster() {return "GET-查詢妖怪";}//等價寫法//@RequestMapping(value = "/monster", method = RequestMethod.POST)@PostMapping("/monster")public String saveMonster() {return "POST-保存妖怪";}//等價寫法@RequestMapping(value = "/monster", method = RequestMethod.PUT)@PutMapping("/monster")public String putMonster() {return "PUT-修改妖怪";}//等價寫法@RequestMapping(value = "/monster", method = RequestMethod.DELETE)@DeleteMapping("/monster")public String deleteMonster() {return "DELETE-刪除妖怪";}
}
2.使用Postman完成測試, 請求url: http://localhost:8080/monster
注意事項和細節
在SpringMVC中我們學過,SpringMVC系列四: Rest-優雅的url請求風格
1.客戶端是Postman
可以直接發送 Put, Delete
等方式請求, 可不設置Filter
.
2.如果要SpringBoot
支持 頁面表單的Rest功能, 則需要注意如下細節
1)Rest
風格請求核心Filter: HiddenHttpMethodFilter
, 表單請求會被HiddenHttpMethodFilter
攔截, 獲取到表單_method
的值, 再判斷是PUT/DELETE/PATCH
(注意: PATCH
方法是新引入的, 是對PUT
方法的補充, 用來對已知資源進行局部更新, PATCH和PUT方法的區別)
2)如果要SpringBoot
支持 頁面表單的Rest功能, 需要在application.yml
啟用filter
功能, 否則無效.
3)修改application.yml
, 啟用filter
功能
spring:mvc:static-path-pattern: /image/** #修改靜態資源訪問 路徑/前綴hiddenmethod:filter:enabled: true #啟動HiddenHttpMethodFilter, 支持rest
4)修改對應的頁面, 然后測試.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>rest</title>
</head>
<body>
<h1>測試rest風格的url, 完成get請求</h1>
<form action="/monster" method="get">u: <input type="text" name="name"><br/><input type="submit" value="點擊提交">
</form>
<h1>測試rest風格的url, 完成post請求</h1>
<form action="/monster" method="post">u: <input type="text" name="name"><br/><input type="submit" value="點擊提交">
</form>
<h1>測試rest風格的url, 完成put請求</h1>
<form action="/monster" method="post"><!--通過隱藏域傳遞_method參數指定值--><input type="hidden" name="_method" value="PUT">u: <input type="text" name="name"><br/><input type="submit" value="點擊提交">
</form>
<h1>測試rest風格的url, 完成delete請求</h1>
<form action="/monster" method="post"><input type="hidden" name="_method" value="delete">u: <input type="text" name="name"><br/><input type="submit" value="點擊提交">
</form>
</body>
</html>
思考題
1.為什么這里 return “GET-查詢妖怪”,返回的是字符串,而不是轉發到對應的資源文件?
1)修改src/main/java/com/zzw/springboot/controller/MonsterController.java
//@RestController
@Controller
public class MonsterController {/*** 解讀* 因為@RestController是一個復合注解,含有@ResponseBody注解,所以sprintboot底層(springmvc),* 在處理return "xxx"時, 會以 @ResponseBody 注解的方式進行解析處理, 即返回字符串"xxx". 而不會使用* 視圖解析器來處理. 如果我們把 @RestController 改成 @Controller, 當你訪問getMonster()時, * 會使用到視圖解析器(如果配置了的話),即如果你有xxx.html, 就會請求轉發到xxx.html, 如果沒有xxx.html, 就會報404.* @return*/@GetMapping("/monster")public String getMonster() {return "GET-查詢妖怪";}@RequestMapping("/go")public String go() {//順序 http://localhost:8088/go// => 1.如果沒有配置視圖解析器, 就看Controller有沒有 /hello// => 2.如果有, 就請求轉發到 /hello, 如果沒有 /hello 映射, 就報錯// => 4.如果配置了視圖解析器, 就走視圖解析器return "hello";}
}
2)瀏覽器請求 http://localhost:8088/go,報 404 錯誤,因為找不到資源文件 hello.html
解決方案
1.如果沒有配置視圖解析器, 訪問 http://localhost:8088/go, 會請求轉發到 /hello
1)修改src/main/java/com/zzw/springboot/controller/HiController.java
@RestController
public class HiController {//@RequestMapping("/hi") //模擬一下, 發現默認請求的路徑和資源的名字沖突@RequestMapping("/hello")public String hi(){return "hi~";}
}
2)測試
2.如果配置了視圖解析器, 訪問 http://localhost:8088/go, 就會請求轉發到 hello.html
1)新建src/main/resources/public/hello.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>hello頁面</title>
</head>
<body>
<h2>hello頁面</h2>
</body>
</html>
2)application.yml
配置視圖解析器
spring:mvc:#盡量用默認的, 因為springboot有個約定優于配置的思想#static-path-pattern: /image/** #修改靜態資源訪問 路徑/前綴hiddenmethod:filter:enabled: true #啟動HiddenHttpMethodFilter, 支持restview: #修改默認的視圖配置
# prefix: / # No mapping for GET /hello.htmlprefix: / #這里需要注意prefix 需要和當前的static-path-pattern保持一致suffix: .html
3)測試
接收參數相關注解
基本介紹
1.SpringBoot 接收客戶端提交數據 / 參數會使用到相關注解.
2.詳細學習 @PathVariable, @RequestHeader, @ModelAttribute, @RequestParam, @CookieValue, @RequestBody
應用實例
●需求:
演示各種方式提交數據/參數給服務器, 服務器如何使用注解接收
@PathVariable
1.創建src/main/resources/public/index.html
JavaWeb系列十: web工程路徑專題
<h1>跟著老韓學springboot</h1>
基本注解:
<hr/>
<!--1. web工程路徑知識:2. / 會解析成 http://localhost:80803. /monster/100/king => http://localhost:8080/monster/100/king4. 如果不帶 /, 會以當前路徑為基礎拼接
/-->
<a href="/monster/100/king">@PathVariable-路徑變量 monster/100/king</a><br/><br/>
</body>
2.創建src/main/java/com/zzw/springboot/controller/ParameterController.java
url占位符回顧
@RestController
public class ParameterController {/*** 1./monster/{id}/{name} 構成完整請求路徑* 2.{id} {name} 就是占位變量* 3.@PathVariable("name"): 這里 name 和 {name} 命名保持一致* 4.String name_ 這里自定義, 這里韓老師故意這么寫* 5.@PathVariable Map<String, String> map 把所有傳遞的值傳入map* 6.可以看下@pathVariable源碼* @return*/@GetMapping("/monster/{id}/{name}")public String pathVariable(@PathVariable("id") Integer id,@PathVariable("name") String name,@PathVariable Map<String, String> map) {System.out.println("id = " + id + "\nname = " + name + "\nmap = " + map);return "success";}
}
3.測試 http://localhost:8088/monster/100/king
@RequestHeader
需求: 演示@RequestHeader
使用.
1.修改src/main/resources/public/index.html
<a href="/requestHeader">@RequestHeader-獲取http請求頭</a><br/><br/>
2.修改ParameterController.java
JavaWeb系列八: WEB 開發通信協議(HTTP協議)
/*** 1. @RequestHeader("Cookie") 獲取http請求頭的 cookie信息* 2. @RequestHeader Map<String, String> header 獲取到http請求的所有信息*/
@GetMapping("/requestHeader")
public String requestHeader(@RequestHeader("Host") String host,@RequestHeader Map<String, String> header) {System.out.println("host = " + host + "\nheader = " + header);return "success";
}
3.測試
@RequestParam
需求: 演示@RequestParam
使用.
1.修改src/main/resources/public/index.html
<a href="/hi?name=趙志偉&fruit=apple&fruit=pear&address=上海&id=3">@RequestParam-獲取請求參數</a><br/><br/>
2.修改ParameterController.java
SpringMVC系列五: SpringMVC映射請求數據
/*** 如果我們希望將所有的請求參數的值都獲取到, 可以通過* @RequestParam Map<String, String> params*/
@GetMapping("/hi")
public String hi(@RequestParam(value = "name") String username,@RequestParam(value = "fruit") List<String> fruits,@RequestParam Map<String, String> params) {System.out.println("username = " + username + "\nfruits = "+ fruits + "\nparams = " + params);return "success";
}
3.測試
@CookieValue
需求: 演示@CookieValue
使用.
1.修改src/main/resources/public/index.html
<a href="/cookie">@CookieValue-獲取cookie值</a>
2.修改ParameterController.java
JavaWeb系列十一: Web 開發會話技術(Cookie, Session)
/*** 因為我們的瀏覽器目前沒有cookie, 我們可以自己設置cookie* 如果要測試, 可以先寫一個方法, 在瀏覽器創建對應的cookie* 說明:* 1. value = "cookie_key" 表示接收名字為 cookie_key的cookie* 2. 如果瀏覽器攜帶來對應的cookie, 那么后面的參數是String, 則接收到的是對應的value* 3. 后面的參數是Cookie, 則接收到的是封裝好的對應的cookie*/
@GetMapping("/cookie")
public String cookie(@CookieValue(value = "cookie_key") String cookie_value,@CookieValue(value = "username") Cookie cookie,HttpServletRequest request) {System.out.println("cookie_value = " + cookie_value+ "\nusername = " + cookie.getName() + "-" + cookie.getValue());Cookie[] cookies = request.getCookies();for (Cookie cookie1 : cookies) {System.out.println("cookie1 = " + cookie1.getName() + "-" + cookie1.getValue());}return "success";
}
3.測試
@RequestBody
需求: 演示@RequestBody
使用.
1.修改src/main/resources/public/index.html
<h1>測試@RequestBody獲取數據: 獲取POST請求體</h1>
<form action="/save" method="post">名字: <input type="text" name="name"><br/>年齡: <input type="text" name="age"><br/><input type="submit" value="提交"/>
</form>
2.修改ParameterController.java
SpringMVC系列十: 中文亂碼處理與JSON處理
/*** @RequestBody 是整體取出Post請求內容*/
@PostMapping("/save")
public String postMethod(@RequestBody String content) {System.out.println("content = " + content);//content = name=zzw&age=23return "sucess";
}
3.測試
content = name=zzw&age=123
@RequestAttribute
需求: 演示@RequestAttribute
使用. 獲取request域的屬性.
1.修改src/main/resources/public/index.html
<a href="/login">@RequestAttribute-獲取request域屬性</a>
2.創建RequestController.java
SpringMVC系列十: 中文亂碼處理與JSON處理
@Controller
public class RequestController {@RequestMapping("/login")public String login(HttpServletRequest request) {request.setAttribute("user", "趙志偉");//向request域中添加的數據return "forward:/ok";//請求轉發到 /ok}@GetMapping("/ok")@ResponseBodypublic String ok(@RequestAttribute(value = "user", required = false) String username,HttpServletRequest request) {//獲取到request域中的數據System.out.println("username--" + username);System.out.println("通過servlet api 獲取 username-" + request.getAttribute("user"));return "success"; //返回字符串, 不用視圖解析器}
}
3.測試…
@SessionAttribute
需求: 演示@SessionAttribute
使用. 獲取session域的屬性.
1.修改src/main/resources/public/index.html
<a href="/login">@SessionAttribute-獲取session域屬性</a>
2.創建RequestController.java
JavaWeb系列十一: Web 開發會話技術(Cookie, Session)
@Controller
public class RequestController {@RequestMapping("/login")public String login(HttpServletRequest request, HttpSession session) {request.setAttribute("user", "趙志偉");//向request域中添加的數據session.setAttribute("mobile", "黑莓");//向session域中添加的數據return "forward:/ok";//請求轉發到 /ok}@GetMapping("/ok")@ResponseBodypublic String ok(@RequestAttribute(value = "user", required = false) String username,HttpServletRequest request,@SessionAttribute(value = "mobile", required = false) String mobile,HttpSession session) {//獲取到request域中的數據System.out.println("username--" + username);System.out.println("通過servlet api 獲取 username-" + request.getAttribute("user"));//獲取session域中的數據System.out.println("mobile--" + mobile);System.out.println("通過HttpSession 獲取 mobile-" + session.getAttribute("mobile"));return "success"; //返回字符串, 不用視圖解析器}
}
3.測試…
🔜 下一篇預告: [即將更新,敬請期待]
📚 目錄導航 📚
- springboot系列一: springboot初步入門
- springboot系列二: sprintboot依賴管理
- springboot系列三: sprintboot自動配置
- springboot系列四: sprintboot容器功能
- springboot系列五: springboot底層機制實現 上
- springboot系列六: springboot底層機制實現 下
- springboot系列七: Lombok注解,Spring Initializr,yaml語法
- springboot系列八: springboot靜態資源訪問,Rest風格請求處理, 接收參數相關注解
…
💬 讀者互動 💬
在學習 Spring Boot 靜態資源訪問和 Rest 風格請求處理的過程中,您有哪些新的發現或疑問?歡迎在評論區留言,讓我們一起討論吧!😊