文章目錄
- 基本介紹
- 接收參數相關注解應用實例
- @PathVariable
- @RequestHeader
- @RequestParam
- @CookieValue
- @RequestBody
- @RequestAttribute
- @SessionAttribute
- 復雜參數
- 基本介紹
- 應用實例
- 自定義對象參數-自動封裝
- 基本介紹
- 應用實例
基本介紹
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.測試…
復雜參數
基本介紹
1.在開發中, SpringBoot在相應客戶端請求時, 也支持復雜參數
2.Map, Model, Errors/BindingResult, RedirectAttributes, ServletResponse, SessionStatus, UriComponentsBuilder, ServletUriComponentBuilder, HttpSession.
3.Map, Model,數據會被放在request
域, 到時Debug一下.
4.RedirectAttribute 重定向攜帶數據
應用實例
說明: 演示復雜參數的使用.
重點: Map, Model, ServletResponse
●代碼實現
1.修改src/main/java/com/zzw/springboot/controller/RequestController.java
SpringMVC系列六: 模型數據
//響應一個注冊請求
@GetMapping("/register")
public String register(Map<String, Object> map,Model model,HttpServletRequest request) {//如果一個注冊請求, 會將注冊數據封裝到map或者model//map中的數據和model中的數據, 會被放入到request域中map.put("user", "趙志偉");map.put("job", "java");model.addAttribute("sal", 6000);//一會我們再測試response使用//請求轉發return "forward:/registerOk";
}@GetMapping("/registerOk")
@ResponseBody
public String registerOk(HttpServletRequest request,@RequestAttribute("user") String user,@RequestAttribute("job") String job,@RequestAttribute("sal") Double sal) {System.out.println("user=" + request.getAttribute("user"));System.out.println("job=" + job);System.out.println("sal=" + sal);return "success";
}
2.瀏覽器輸入 http://localhost:8088/register , 打斷點測試
SpringMVC系列十三: SpringMVC執行流程 - 源碼分析
進入目標方法
剖析 request 對象
3.繼續修改 register()
方法
JavaWeb系列十一: Web 開發會話技術(Cookie, Session)
//響應一個注冊請求
@GetMapping("/register")
public String register(Map<String, Object> map,Model model,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {//如果一個注冊請求, 會將注冊數據封裝到map或者model//map中的數據和model中的數據, 會被放入到request域中map.put("user", "趙志偉");map.put("job", "java");model.addAttribute("sal", 6000);//一會我們再測試response使用//演示創建cookie, 并通過response 添加到瀏覽器/客戶端Cookie cookie = new Cookie("email", "978964140@qq.com");response.addCookie(cookie);//請求轉發return "forward:/registerOk";
}
4.測試
自定義對象參數-自動封裝
基本介紹
1.在開發中, SpringBoot在響應客戶端/瀏覽器請求時, 也支持自定義對象參數
2.完成自動類型轉換與格式化
3.支持級聯封裝
應用實例
●需求說明:
演示自定義對象參數使用,完成自動封裝,類型轉換。
●代碼實現
1.創建public/save.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>添加妖怪</title>
</head>
<body>
<form action="?" method="?">編號: <input name="" value=""><br/>姓名: <input name="" value=""><br/>年齡: <input name="" value=""><br/>婚否: <input name="" value=""><br/>生日: <input name="" value=""><br/>坐騎名稱: <input name="" value=""><br/>坐騎價格: <input name="" value=""><br/><input type="submit" value="保存"/>
</form>
</body>
</html>
2.創建src/main/java/com/zzw/springboot/bean/Car.java
@Data
public class Car {private String name;private Double price;
}
3.創建src/main/java/com/zzw/springboot/bean/Monster.java
@Data
public class Monster {private Integer id;private String name;private Integer age;private Boolean maritalStatus;private Date birthday;private Car car;
}
4.修改ParameterController.java
//處理添加monster的方法
@PostMapping("/saveMonster")
public String saveMonster(Monster monster) {System.out.println("monster = " + monster);return "success";
}
5.回填public/save.html
<form action="saveMonster" method="post">編號: <input name="id" value="100"><br/>姓名: <input name="name" value="張三"><br/>年齡: <input name="age" value="30"><br/>婚否: <input name="maritalStatus" value="未婚"><br/>生日: <input name="birthday" value="1994-01-01"><br/><input type="submit" value="保存"/>
</form>
6.自動封裝需要用到自定義轉換器. 接下來, 繼續學習自定義轉換器.
🔜 下一篇預告: [即將更新,敬請期待]
📚 目錄導航 📚
- springboot系列一: springboot初步入門
- springboot系列二: sprintboot依賴管理
- springboot系列三: sprintboot自動配置
- springboot系列四: sprintboot容器功能
- springboot系列五: springboot底層機制實現 上
- springboot系列六: springboot底層機制實現 下
- springboot系列七: Lombok注解,Spring Initializr,yaml語法
- springboot系列八: springboot靜態資源訪問,Rest風格請求處理, 接收參數相關注解
…
💬 讀者互動 💬
在學習 Spring Boot 靜態資源訪問和 Rest 風格請求處理的過程中,您有哪些新的發現或疑問?歡迎在評論區留言,讓我們一起討論吧!😊