springmvc已經幫我們封裝好了這些對象,只需在方法參數上使用所需要的對象即可
- @Controller
- public class ServletController {
-
- /**
- * 只要在控制器方法上加入request,response,session類型的參數,springmvc框架會把這些對象準備好作爲方法參數傳入
- * 建議不要直接在方法參數上使用 Servlet 的(request,response,session)對象
- * @param request
- * @param response
- * @param session
- * @return
- */
- @RequestMapping("/s1")
- public String s1(HttpServletRequest request, HttpServletResponse response, HttpSession session){
- System.out.println("獲取實際請求路徑:"+request.getRequestURI());
- System.out.println("獲取客戶端的ip:"+request.getRequestURI());
- System.out.println("response的對象:"+response);
- response.addCookie(new Cookie("user","chen"));
- System.out.println("session的對象:"+session);
-
- return "hello";
- }
- }
SpringMVC頁面轉發:
服務器內部跳轉(forward)和 客戶端重定向(redirect)
1) 轉發
(1) 轉發到JSP頁面: 請求處理方法返回字符串,默認使用服務器內部跳轉 ( request.getRequestDispatcher("指定頁面").forward(request,response) )
示例: return "hello"; (視圖名: 視圖解析器會根據視圖名拼接成正確的訪問路徑 " /hello.jsp")
(2)轉發到服務器內部的請求:在返回的字符串前面加入 “ forward:/ 路徑名 ”
示例: return " forward:/ main ";( 在服務器內部跳轉到名爲 main 的請求處理方法中)
2)重定向
(1)重定向到 JSP頁面:在返回字符串的前面加上 “ redirect:/xxx.jsp ”
示例:return " redirect:/xxx.jsp "
***注意:
由於客戶端重定向(redirect)相當於在瀏覽器重新發一次請求,所以不能訪問 WEB-INF 下的資源文件,而且資源文件必須寫完整(xxx.jsp),因爲此時的視圖解析器不會將該字符串進行解析,拼接
(2)重定向到 Controller 上 : 在返回的字符串前面加上 “ redirect:/路徑名 ”
示例: return " redirect:/main "; ( 客戶端重定向到名爲 main 的請求處理方法中 )
Spring MVC 傳值:
方法一:使用session傳值 :
優點:信息相對比較安全,可以傳輸任意類型的數據
缺點:每個session都會佔用服務器的內存
測試代碼:
- @Controller
- public class RedirectController {
-
- /**
- * 方法一: 利用 HttpServletResponse 對象的重定向
- * session 傳值:
- * 優點: 安全性高,可傳任意類型的數據
- * 缺點: 每個session都會佔用服務器的內存
- *
- * @param response
- * @return
- * @throws IOException
- */
- @RequestMapping("/r1")
- public String r1(HttpServletResponse response, HttpSession session) throws IOException {
- System.out.println("r1");
- // 一次會話之內有效
- session.setAttribute("name","chen");
-
- //response.sendRedirect("/r2");
- // 在視圖名前面添加 `redirect:`,這時候springmvc就會把字符串當做重定向進行跳轉,而不是再通過視圖解析器進行解析
- return "redirect:/r2";
- }
-
- @RequestMapping("/r2")
- public String r2(HttpSession session){
- System.out.println("r2");
- System.out.println(session.getAttribute("name"));
-
- // 需要手動移除 session 的值
- session.removeAttribute("name");
- return "hello";
- }
- }
方法二: 利用重定向後面跟上請求參數的方法
優點: 不會佔用服務器的內存,可以向站外地址傳值
缺點: 信息不安全,暴露在地址欄後面,可以傳輸的數據類型和數據大小有限制
測試代碼:
- @Controller
- public class RedirectController {
-
- /**
- * 利用重定向地址後跟請求參數的方式
- * 優點: 不會佔用服務器內存,可以向站外地址傳參
- * 缺點: 安全性不高,數據大小有限制,不能傳 複雜的 數據類型
- * @return
- */
- @RequestMapping("/r3")
- public String r3(){
- System.out.println("r3");
- return "redirect:/r4?username=zhangsan";
- }
-
- @RequestMapping("/r4")
- public String r4(String username){
- System.out.println("r4");
- System.out.println("username: "+username);
- return "hello";
- }
-
-
- }
方法三:使用 Spring MVC提供的傳參的對象(RedirectAttributes):專門在重定向時傳參,綜合了上面兩種方法
RedirectAttributes : 傳參,專門在重定向時傳參
@ModelAttributes: 接收值
方式一(重定向後面跟請求參數的方式): redirect.addAttribute("參數名",參數值);
方式二(使用session傳值的方式):redirect.addFlashAttribute("參數名",參數值);
測試代碼:
- @Controller
- public class RedirectController {
-
- /**
- * SpringMVC提供的重定向方法:結合了上面兩種方式的傳參方式
- * RedirectAttributes : 傳參,專門在重定向時傳參
- * @ModelAttributes: 接收值
- * 方式一(重定向後面跟請求參數的方式): redirect.addAttribute("username","chen");
- * 方式二(使用session傳值的方式):redirect.addFlashAttribute("username","kobe");
- *
- * @param redirect
- * @return
- */
-
- @RequestMapping("/r5")
- public String r5(RedirectAttributes redirect){
- System.out.println("r5");
- // 採用的是 重定向後面跟請求參數的方式
- redirect.addAttribute("username","chen");
-
- // 採用的是 session 的傳值方式
- redirect.addFlashAttribute("username","kobe");
- return "redirect:/r6";
- }
-
- @RequestMapping("/r6")
- public String r6(@ModelAttribute("username")String name){
- System.out.println("r6");
- System.out.println("username: "+name);
- return "hello";
- }
- }
Spring MVC中的異常處理:
SpringMVC提供了兩種方式
1)使用 SpringMVC提供的簡單異常處理器 SimpleMapperingExceptionResolver (需要配合 .xml 文件來配置)
2)使用註解@ExceptionHandler( 用在方法上) 實現局部異常處理或使用註解@ControllerAdvice(類)實現全局統一處理異常
***注意:不建議在請求處理方法中寫異常處理塊(catch),因爲這種處理方式非常繁瑣,而且一旦改變異常處理方式, 需要修改大量的代碼,耦合性較高
方式一: 使用 SimpleMapperingExceptionResolver 進行異常處理
1)在 spring.xml 文件中配置:
- <!--
- p:defaultErrorView="error":表示所有沒有指定的異常,都跳轉到默認異常處理頁面 error.jsp
- p:exceptionAttribute="ex" :表示異常處理頁面中訪問的異常對象變量名是 ex
- exceptionMappings: 表示映射的異常,接受參數是一個 Properties
- key:是異常類名, values:處理異常的頁面
-
- -->
-
- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
-
- p:defaultErrorView="error"
- p:exceptionAttribute="ex"
- >
- <property name="exceptionMappings">
- <props>
- <prop key="java.lang.ArrayIndexOutOfBoundsException">error1</prop>
- <prop key="java.lang.ArithmeticException">error2</prop>
- </props>
- </property>
- </bean>
2)模擬異常的處理方法:
- @RequestMapping("/testSimpleMapingExceptionResolver")
- public String testSimpleMapingExceptionResolver(@RequestParam("i") int i){
- String[] values=new String[10];
- System.out.println(values[i]);
- return "success";
-
- }
3)error.jsp頁面:
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ page isELIgnored="false" %>
- <html>
- <head>
- <title>Title</title>
-
- </head>
- <body>
- 錯誤頁面!
- <br>
- ${requestScope.ex.message}
- </body>
- </html>
方式二: 使用註解 @ExceptionHandler( 用在方法上) 或 @ControllerAdvice(類) 實現處理異常
1)@ExceptionHandler: 加在方法上,並且在運行時有效( 只能捕獲 本Controller 中發生的異常)
- @Controller
- public class ExceptionController {
-
- /**
- * springmvc 幫我們自動捕獲異常
- * @ExceptionHandler(ArithmeticException.class): 只能精確匹配異常類型,匹配到了,則執行該方法,若不匹配,則繼續報錯
- * @ExceptionHandler(Exception.class): 若沒匹配到該精確類型,則執行該異常的方法
- *
- * ***注意***: 以上自動捕獲異常值捕獲 ***本Controller*** 發生的異常,別的 Controller 若發生異常,則無法捕獲
- * @return
- */
- @RequestMapping("/e2")
- public String e2(){
- System.out.println("e2");
- int i = 1/0;
- int[] arr = new int[5];
- System.out.println(arr[6]);
- return "hello";
- }
-
- @ExceptionHandler(ArithmeticException.class)
- public String exception1(ArithmeticException e){
- System.out.println("錯誤信息:"+e.getMessage());
-
- return "error";
- }
-
- @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
- public String exception2(ArithmeticException e){
- System.out.println("錯誤信息:"+e.getMessage());
-
- return "error";
- }
-
-
- }
2)使用 @ControllerAdvice : 它是一個控制器增強功能註解,加在類上, 會將該類中所有使用了 @ExceptionHandler 註解的方法都應用到請求處理方法上
測試代碼:先精確匹配異常類型,若匹配不到,則最後再匹配 Exception 類
- // 告知spring容器這是個 **全局捕獲異常類**
- @ControllerAdvice
- public class GlobalExceptionAdvice {
-
- @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
- public String exception1(ArrayIndexOutOfBoundsException e){
- System.out.println("數組越界:"+e.getMessage());
- return "error";
- }
-
- @ExceptionHandler(Exception.class)
- public String exception2(Exception e){
- System.out.println(e.getMessage());
- return "error";
- }
-
- @ExceptionHandler(ArithmeticException.class)
- public String exception3(ArithmeticException e){
- System.out.println(e.getMessage());
- return "error";
- }
- }
***注意:
1) @EceptionHandler 該方法只能捕獲本控制器類出現的異常
2) 匹配異常類型時,會匹配一個最接近的異常類型
3) @ControllerAdvice : 全局控制器的通知類, 加在通知類上,這樣當某個控制器出現異常時, 先找本類的異常處理器,如果找不到,那麼再到通知類中找全局的異常處理器
SpringMVC文件上傳:
SpringMVC對本間上傳提供了直接的支持,使用 MultipartResolver(文件解析器) 實現的, 爲了來解決表單提交的數據格式是 enctype = "Multipart/form-data", 瀏覽器就會採用二進制的方式來處理表單數據
1)在 pom.xml 中導入文件上傳所需的 commons-fileupload-1.3.3.jar 和 commons-io-2.2.jar 兩個jar 包
- <!-- 文件上傳(可選) -->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.3</version>
- </dependency>
2)在 spring.xml 中配置文件解析器
- <!-- 配合文件上傳而使用的 文件解析器-->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 設置文件上傳大小,單位:字節-->
- <property name="maxUploadSize" value="100000"/>
-
- <!-- 請求的編碼格式,必須與JSP的 pageEncoding 的屬性一致,默認爲 ISO-8859-1 -->
- <property name="defaultEncoding" value="UTF-8">
- </bean>
3)編寫 文件 上傳 的 jsp 頁面
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <form action="/upload" method="post" enctype="multipart/form-data">
- <input type="file" name="file">
- <input type="submit" value="提交">
- </form>
- </body>
4)編寫文件上傳的控制器類: springmvc會將上傳的文件綁定到 MultipartFile 對象中
MultipartFile 對象: 可以獲取上傳文件的內容,文件名,大小等數據
- byte[] getBytes(): 獲取文件數據
- String getContentType(): 獲取文件MIME類型,如 image/jpeg
- InputStream getInputStream(): 獲取文件流
- String getName(): 獲得表單中文件組件的名稱
- String getOriginalFilename(): 獲得上傳文件的名稱
- long getSize(): 獲得文件的字節大小,單位:byte
- boolean isEmpty(): 判斷是否有上傳的文件
- void transerTo(File dest): 將上傳的文件保存到一個目標文件中
- @Controller
- public class FileUploadController {
- @RequestMapping("/upload")
- public String upload(MultipartFile file) throws IOException {
- System.out.println("上傳的文件類型:"+file.getContentType());
- System.out.println("上傳的文件名:"+file.getOriginalFilename());
- System.out.println("上傳的文件大小:"+file.getSize());
- System.out.println("上傳的文件是否爲空:"+file.isEmpty());
-
- // 將上傳的文件保存到本地
- file.transferTo(new File("G:\\"+file.getOriginalFilename()));
-
- return "hello";
- }
- }
SpringMVC中緩存的配置:
@Cacheable( cacheNames="緩存的名字"): 加在方法上
***工作原理:
在執行該方法之前,先檢查緩存中是否有這條記錄,如果有,則直接返回緩存中的記錄,不執行該方法,
若該緩存中沒有存儲該條記錄,則執行該方法,將該方法的返回值存入該緩存中,以便於下一次的查找;
@CacheEvict( cacheNames = "緩存名字",allEntries = true) : 加在方法上 (allEntries: 該緩存中的所有記錄)
*** 工作原理:
將該緩存下的所有記錄都清空
@CachePut( cacheNames="緩存名字"):加在方法上
*** 工作原理:
總是會執行該方法,每次都把返回結果更新進該緩存中
測試代碼:
在 sprin.xml 中添加緩存配置:
- <!-- 緩存的管理器 -->
- <bean id="cacheManager" class="org.springframework.cache.concurrent.ConcurrentMapCacheManager">
- <!-- 管理緩存區域 -->
- <property name="cacheNames">
- <list>
- <value>user</value>
- <value>order</value>
- <value>product</value>
- </list>
- </property>
- </bean>
-
- <!-- 啓用緩存相關的註解及支持
- @Cacheable
- @CacheEvict
- @CachePut
- -->
- <cache:annotation-driven/>
- @Controller
- public class CacheController {
-
- @Autowired
- private UserService userService;
-
- @RequestMapping("/cache1")
- @ResponseBody
- @Cacheable(cacheNames = "user")
- /**
- * 找到user的緩存
- * Cache userCache = ;
- * User user = userCache.get(key#id);
- * if(user == null) {
- * user = 調用findById方法查詢數據庫;
- * userCache.put("key#id", user);
- * }
- */
- public User findById(int id) {
- return userService.findById(id);
- }
-
- @RequestMapping("/update")
- @ResponseBody
- @CacheEvict(cacheNames = "user", allEntries = true) // 讓緩存的內容失效
- public String update() {
- System.out.println("執行了修改方法");
- return "update successful..";
- }
-
- @RequestMapping("/update2")
- @ResponseBody
- @CachePut(cacheNames = "user") // 思路將方法的執行結果替換緩存的內容
- public User update2(int id) {
- System.out.println("執行了Update2");
- User user = userService.findById(id);
- return user;
- }
-
- }
Ajax: (Asynchronous JavaScript And XML )異步的 JavaScript 和 XML 不是一種新的編程語言, 而是一種頁面無刷新技術,在頁面不刷新的情況下與服務器進行交互,是一種創建更好,更快以及交互性更強的 web技術,基於 JavaScript ,html,css ,xml 的新用法
Ajax的工作原理: 只刷新局部頁面
相當於在用戶和服務器之間加了—個中間層,使用戶操作與服務器響應異步化。並不是所有的用戶請求都提交給服務器,像—些數據驗證和數據處理等都交給Ajax引擎自己來做, 只有確定需要從服務器讀取新數據時再由Ajax引擎代爲向服務器提交請求
- JavaScript:更新局部的網頁
- XML:一般用於請求數據和響應數據的封裝
- XMLHttpRequest對象:發送請求到服務器並獲得返回結果
- CSS:美化頁面樣式
- 異步:發送請求後不等返回結果,由回調函數處理結果
原理圖:
同步提交請求: 提交請求後,只有等到返回響應,纔會繼續執行下面的操作, 否則將會一直等待下去
異步提交請求:提交請求後,無需等待返回響應,就可以繼續執行下面的操作
XHRHttpRequest: 整個Ajax技術的核心,它提供了異步發送請求的能力
屬性
readyState:類型short;只讀: 響應狀態
responseText:類型String;只讀 : 獲得字符串(JSON )形式的響應數據。
responseXML:類型Document;只讀 獲得 XML 形式的響應數據。
status:類型short;只讀 返回狀態碼, 200: ok, 404:錯誤…
方法:
open(method,URL,async) :建立與服務器的連接
參數1: method參數指定請求的HTTP方法,典型的值是GET或POST
參數2: URL參數指請求的地址
參數3: async參數指定是否使用異步請求,其值爲true或false
send(content) : 發送請求
content參數指定請求的參數
setRequestHeader(header,value):設置請求的頭信息
Ajax同步發送請求:
1. 創建xhr對象
2. 發送請求
3. 接收響應
4. 將返回的 json結果 轉換 js對象
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
-
- <video src="video/tomcatcluster.mp4" controls width="500"></video>
-
- <input type="text" name="content" id="c">
- <input type="button" value="提交評論" οnclick="sendRequest()">
- <hr>
- <div style="width:100%; height: 100px; border: 1px solid black;" id="d1"></div>
-
- <script>
-
- //同步方式接收響應
-
- function sendRequest() {
- // 1. 創建xhr對象
- var xhr = new XMLHttpRequest();
-
- // 2. 發送請求
- // 獲取文本框評論的內容
- var c = document.getElementById("c").value;
- xhr.open("get","/pinglun?content="+c, false);
- xhr.send();
- // 3. 接收響應
- var text = xhr.responseText; // "" // 拿到的responseText是json格式的 , 例如: {"content":"分階段"}
- // 4. 將json結果轉換js對象
- var obj = JSON.parse(text);
- document.getElementById("d1").innerText = obj.content;
- }
-
-
- </script>
- </body>
- </html>
Ajax異步發送請求:
1. 創建xhr對象
2. 定義響應事件
3. 發送請求
4. 接收響應
5. 將json結果轉換js對象
-
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
-
- <video src="video/tomcatcluster.mp4" controls width="500"></video>
-
- <input type="text" name="content" id="c">
- <input type="button" value="提交評論" οnclick="sendRequest()">
- <hr>
- <div style="width:100%; height: 100px; border: 1px solid black;" id="d1"></div>
-
- <script>
-
- // 異步方式接收響應
- function sendRequest() {
- // 1. 創建xhr對象
- var xhr = new XMLHttpRequest();
-
- // 2. 定義響應事件
- xhr.onload = function(){
- // 4. 接收響應
- var text = xhr.responseText; // "" // 拿到的responseText是json格式的 , 例如: {"content":"分階段"}
- // 5. 將json結果轉換js對象
- var obj = JSON.parse(text);
- document.getElementById("d1").innerText = obj.content;
- };
-
- // 3. 發送請求
- // 獲取文本框評論的內容
- var c = document.getElementById("c").value;
- xhr.open("get","/pinglun?content="+c, true);
- xhr.send();
-
- }
- </script>
- </body>
- </html>
註解:在spring.xml 中 啓用 mvc相關的註解功能 <mvc:annotation-driven/>
SpringMVC中的註解有很多,都在 org.springframework.web.bind.annotation 包下
主要分爲六大類:(根據處理 request 的內容不同劃分)
1)處理請求參數和內容部分的註解:
(1)@Controller: 加在類上,用來指示該類是一個控制器類,使用註解可以使得該控制器支持 同時處理多個請求動作,更加靈活
工作原理: 使用了 @Controller 的註解會被Spring的掃描機制查找到,並檢測該類中的方法是否使用了 @RequestMapper 註解,使用了該註解的方法纔是真正處理請求的處理器,匹配對應的路徑進行處理請求
(2)@RequestMapper: 加在 類或方法上,指示哪一個類或者方法來處理相對應的請求動作
測試代碼:
- @Controller
- @RequestMapping("/user")
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- @RequestMapping("/findById")
- public User findById(int id) {
- return userService.findById(id);
- }
-
- @RequestMapping("/a")
- public User a(int id) {
- return userService.findById(id);
- }
-
-
- }
(3)@ResponseBody: 加在方法上,將方法返回的對象,通過適當的 HttpMessageConverter 轉換爲指定格式 寫入到 Response 對象的 body 數據區域中,一般用於返回 JSON 或 XML 數據
測試代碼: 返回 JSON格式的數據
- @Controller
- @RequestMapping("/user")
- public class UserController {
-
- @Autowired
- private UserService userService;
-
-
- @RequestMapping("/exists")
- @ResponseBody // {"exists", true}
- public Map<String,Object> exists(String username) throws InterruptedException {
- boolean exists = userService.exists(username);
- Thread.sleep(2000);
- Map<String, Object> map = new HashMap<>();
- map.put("exists", exists);
- return map;
- }
- }
(4) @RequestBody: 加在方法參數上,用來處理 Content-type: 不是 application/x-www-form-urlencoded編碼 的內容,而是例如: application/xml ,application/json 等數據格式時,使用該註解, 通過使用 HandlerAdapter 配置的 HttpMessageConverters 來解析 JSON 或 XML數據, 讓後綁定到相對應的 bean 上(把請求體中的json字符串再還原爲java對象)
測試代碼: jsp頁面
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <input type="button" value="發送表單格式請求" οnclick="sendRequest()">
- <input type="button" value="發送json格式請求" οnclick="sendJsonRequest()">
- <script>
- function sendRequest() {
- var xhr = new XMLHttpRequest();
- xhr.onload = function(){...};
- xhr.open("post", "/post", true);
- // 告訴服務器,請求體的格式是:表單格式
- xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
- xhr.send("username=zhangsan"); // 包含的是請求體的內容
- }
- function sendJsonRequest() {
- var xhr = new XMLHttpRequest();
- xhr.onload = function(){...};
- xhr.open("post", "/post2", true);
- xhr.setRequestHeader("content-type", "application/json");
- var user = {"id":1, "name":"李四"}; // [object Object]
- // 要把js對象轉爲json字符串才能發送
- xhr.send(JSON.stringify(user))
- }
- </script>
- </body>
- </html>
Controller 處理:
- @Controller
- public class PostController {
-
- @ResponseBody
- @RequestMapping("/post")
- public String post(String username) {
- System.out.println("username:" +username);
- return "ok";
- }
-
- @ResponseBody
- @RequestMapping("/post2") // @RequestBody的作用就是把請求體中的json字符串再還原爲java對象
- public String post2(@RequestBody User user) {
- System.out.println("user對象是:"+user);
- return "ok";
- }
-
- }
其他註解: @RequestParam,@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,
@PatchMapping,@RequestPart,@RestController
2)處理請求 URL 部分的註解:@PathVariable, @MatrixVariable,@CrossOrigin
(1)@PathVariable: 加在方法參數上,可以非常方便的獲取請求 URL 中的動態參數(路徑參數)
- @RequestMapping("/test4/{id}/{name}")
- public String test4(@PathVariable("id")int x,@PathVariable("name")String n){
- System.out.println("name: "+n+" id: "+x);
- return "hello";
- }
(2)@MatrixVariable: 加在方法參數上,拓展了URL請求地址的功能,多個請求參數可用 “ , ”分開 一般用於進行多條件的組合查詢
***注意:
springMVC默認是不開啓 @MatrixVariables 註解功能的
需要使用時,在 spring.xml 中更改爲 < mvc:annotation-driven enable-matrix-variables="true" /> 開啓註解功能
- // 查詢的URL : http://loaclhost/test4/1;name=chen;age=18
-
- @RequestMapping("/test4/{id}")
- public String test4(
- @PathVariable("id")int x,
- @MatrixVariable(vaule = "name",pathVar="id") String name,
- @MatrixVariable(vaule = "age",pathVar="id")int age,
- ){
- System.out.println("name: "+name+" id: "+id+" age:"+age);
- return "hello";
- }
-
-
3)處理請求頭部分的註解: @RequestHeader, @CookieValue
(1)@CookieValues(" 參數名") : 加在方法參數上,用於將請求的 cookie 數據映射到功能處理方法的參數上
支持屬性:
name :請求參數綁定的名稱
value: name屬性的別名
required:指定參數是否必須綁定
defaultValues: 如果沒有傳遞參數而使用默認值
測試代碼:
- @Controller
- public class ServletController {
-
- /**
- * @CookieValue("user"): 在請求紅找到一個名爲 user 的cookie的值
- *
- * @param username
- * @return
- */
- @RequestMapping("/s2")
- public String s2(@CookieValue("user")String username){
- System.out.println("獲取到請求cookie的值:"+username);
- return "hello";
- }
- }
(2) @RequestHeader: 加在方法參數上,將請求頭的信息數據映射到方法參數上
4)處理屬性類型的註解:@RequestAttribute,@SessionAttribute,@SessionAttributes,@ModelAttribute
(1) @RequestAttribute: 加在方法參數上,用於獲取 request作用域 中的數據
(2)@SessionAttribute: 加在方法參數上,用於獲取 session作用域中的數據
(3)@SessionAttributes: 加在類上,允許我們有選擇的指定Model中的哪些屬性轉存入 session 作用域中
(4) @ModelAttribute:加在方法上,用於將請求參數綁定到對象,然後存入request作用域中
***注意: 使用了 @ModelAttribute 註解的方法會在Controller每個方法執行前被執行
5)處理異常類型的註解:@ExceptionHandler , @ControllerAdvice, @RestControllerAdvice, @ResponseStatus
(1) @ExceptionHandler: 加在方法上,運行時有效,參數:value=異常類型名.class
(2) @ControllerAdvice: 加在類上,經常配合@ExceptionHandler做全局異常處理
(3) @ResponseStatus: 加在類或方法上,處理異常最簡單的方式,一般用於自定義的異常類
6)綁定表單數據的註解: @InitBinder