二、springMVC之RequestMapping和繫結引數註解
一、概述:
配置方式:
同HelloWord的配置方式;
目錄結構:
@RequestMapping:
@RequestMapping除了可以使用請求URL對映請求外,還可以使用請求方法、請求引數及請求頭對映請求;
@RequestMapping的value、method、params及heads分別表示請求URL、請求方法、請求引數及請求頭的對映條件,他們之間的與的關係,聯合使用多個條件可讓請求對映更加精確化。
修飾類
關於@RequestMapping除了修飾方法,還可用來修飾類 類定義處:提供初步的請求對映資訊。
方法定義處:提供進一步的分對映資訊。
類定義處標記的@RequestMapping 限定了處理器類可以
處理器類可以定義多個處理方法,處理來自/springmvc下的請求;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public classRequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping("/testRequestMaping") 12 public String hello() { 13 System.out.println("testRequestMaping"); 14 return SUCCESS; 15 } 16 }
index.jsp:
a標籤的herf 屬性 為RequestMapping的 類的修改 和方法的修飾value的拼接;
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="springmvc/testRequestMaping">hello</a> 11 </body> 12 </html>
success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index頁面點選 hello 跳轉到 success.jsp頁面 且控制檯列印:testRequestMaping;
使用method屬性來指定請求方式
RequestMapping(value="testMethod",method=RequestMethod.POST):
- value:指定URL
- method:指定請求方式
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * 14 * 常用:使用method屬性來指定請求方式 15 * 16 * @return 17 */ 18 @RequestMapping(value = "/testMethod", method = RequestMethod.POST) 19 public String testMethod() { 20 System.out.println("testMethod"); 21 return SUCCESS; 22 } 23 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="/springmvc/testMethod" method="POST"> 11 <input type="submit" value="post提交"> 12 </form> 13 </body> 14 </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index頁面點選post提交 跳轉到 success.jsp頁面 且控制檯列印:testMethod;
使用params來更加精確的對映請求
params={"username", "age!=10","!dept"}引數說明:
- 請求引數中必須包含 username,username有沒有值都沒有關係;
- 請求引數必須包含age且age不等於10 age有沒有都沒關係,
- 請求引數不能包含dept;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 /** 12 * 13 * 瞭解;可以使用params和headers來更加精確的對映請求 params和headers支援簡單的表示式 14 * 15 * @return 16 */ 17 @RequestMapping(value = "/testParamsAndHeaders", params = { "username", "age!=10","!dept" }) 18 public String testParamsAndHeaders() { 19 System.out.println("testParamsAndHeaders"); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=10">testParamsAndHeaders_username_age10</a> 11 <br> 12 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=11">testParamsAndHeaders_username_age11</a> 13 <br> 14 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=11&gender=1">testParamsAndHeaders_username_age11_gender</a> 15 <br> 16 <a href="/springmvc/testParamsAndHeaders?age=11&gender=1">testParamsAndHeaders_age11_gender</a> 17 <br> 18 </body> 19 </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp的頁面如下,
如果點選testParamsAndHeaders_username_age10,則顯示錯誤資訊;原因是age=10,而param中規定引數!=10;
如果點選testParamsAndHeaders_username_age11,則成功跳轉到success 且 控制檯列印testParamsAndHeaders;
如果點選testParamsAndHeaders_username_age11_gender,則成功跳轉到success且 控制檯列印testParamsAndHeaders;
如果點選testParamsAndHeaders_age11_gender,則顯示錯誤資訊;原因是沒有username,而param中規定引數中有username,所以引數中必須帶有username;
使用headers來更加精確的對映請求
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping(value = "/testHeaders", headers = { "Accept-Language=zh-CN,zh;q=0.9" }) 12 public String testHeaders() { 13 System.out.println("testHeaders"); 14 return SUCCESS; 15 } 16 17 @RequestMapping(value = "/testHeaders/enus", headers = { "Accept-Language=en-US,zh;q=0.9" }) 18 public String testHeadersEnus() { 19 System.out.println("testHeaders"); 20 return SUCCESS; 21 } 22 }
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="/springmvc/testHeaders">testHeaders</a> <br> <a href="/springmvc/testHeaders/enus">testHeaders_enus</a> <br> </body> </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp 執行結果如下,當點選testHeaders ,跳轉到 success.jsp頁面 且控制檯列印testHeaders,
點選testHeaders_enus 報錯,原因是 headers = { "Accept-Language=en-US,zh;q=0.9" },與瀏覽器的Accept-Language不一致導致請求失敗;
@RequestMapping URL支援Ant風格的請求(萬用字元)
- ?:匹配檔名中的一個字元:
- *:匹配檔名中的任意字元
- **:匹配多層路徑;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping("/testAntPath/*/abc/dd/**/end?") 12 public String testAnt() { 13 System.out.println("testAnt"); 14 return SUCCESS; 15 } 16 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testAntPath/test/abc/dd/test/test/end11">testAnt</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp 的執行效果如下圖;點選testAnt,會出現錯誤,原因是/springmvc/testAntPath/test/abc/dd/test/test/end11 end11多了一個1,因為@RequestMapping("/testAntPath/*/abc/dd/**/end?") 且?匹配一個字元,這裡end11 多了一個字元;所以不成功;把end11改為end1 ,再點選testAnt,會跳轉到success 頁面,且控制檯列印:testAnt;
@PathVariable對映URL繫結的佔位符到目標方法的引數中:
@RequestMapping url中的佔位符,必須和@PathVariable中的值一致,@PathVariable中的值可以和引數值相同也可以不相同;
即 @RequestMapping("/testPathVariable/{id}/{name}");中的{id} 必須與@PathVariable("id") String id ,中的@PathVariable("id") 值相同;與String id 可以相同或者不相同。
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 @RequestMapping("/testPathVariable/{id}/{name}") 13 public String testPathVariable(@PathVariable("id") String id, @PathVariable("name") String names) { 14 System.out.println("testPathVariable id:" + id + ",name:" + names); 15 return SUCCESS; 16 } 17 }
index.jsp:
a標籤中的佔位符必須數量必須和@RequestMapping("/testPathVariable/{id}/{name}")中的數量一致,否則報錯;
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testPathVariable/aaa/bb">testPathVariable</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp顯示如下;點選testPathVariable,跳轉到success頁面,同時控制檯列印 testPathVariable id:aaa,name:bb
REST( Representational State Transfer )
說明:
State Transfer 為 "狀態傳輸" 或 "狀態轉移 ",Representational 中文有人翻譯為"表徵"、"具象",合起來就是 "表徵狀態傳輸" 或 "具象狀態傳輸" 或 "表述性狀態轉移"。可以理解為:(資源)表徵狀態傳輸;
- 資源:就是網路上的一個實體,換言之就是一個具體的資訊。(如圖片,文字。。。)可以用URI 指向它。URI為每一個資源識別符。
- 表徵:可以理解為資源的傳輸形式(文字可以用 txt;可以用HTML;可以用JSON)。
- 狀態轉換:HTTP協議 無狀態;如果客戶需要操作伺服器,必須通過某種手段,讓伺服器發生狀態轉換。http協議裡面,4個表示操作的動詞,GET、POST、PUT、DELETE。對應著 獲取、新增、修改、刪除。
示例:
- '/order/1 http get' 得到ID=1的order
- '/order http POST' 新增的order
- '/order/1 http PUT' 更新ID=1的order
- '/order/1 http DELETE' 刪除ID=1的order
例項驗證
為了實現put 和 delete的效果,web.xml中需要配置HiddenHttpMethodFilter ,可以把post請求轉為delete or put請求 。
1 <!-- 配置HiddenHttpMethodFilter :可以把post請求轉為delete or put請求 --> 2 3 <filter> 4 <filter-name>HiddenHttpMethodFilter</filter-name> 5 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 6 </filter> 7 <filter-mapping> 8 <filter-name>HiddenHttpMethodFilter</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
web.xml配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <display-name>HelloWorld</display-name> 7 <!-- 配置DispatcherServlet(快捷鍵 alt +/) --> 8 <servlet> 9 <servlet-name>springDispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置DispatcherServletd 一個初始化引數:配置springmvc配置檔案的位置和名稱 --> 12 <!-- 實際上也可以不通過 contextConfigLocation 來配置Springmvc的配置檔案,而是用預設的 即預設的配置檔案為 13 /WEB-INF/<servlet-name>-servlet.xml 本專案預設位置配置檔案即為: /WEB-INF/springDispatcherServlet-servlet.xml --> 14 <init-param> 15 <param-name>contextConfigLocation</param-name> 16 <param-value>classpath:spring.xml</param-value> 17 </init-param> 18 <!-- 表示springDispatcherServlet在載入的時候被建立 --> 19 <load-on-startup>1</load-on-startup> 20 </servlet> 21 22 <!-- Map all requests to the DispatcherServlet for handling --> 23 <servlet-mapping> 24 <servlet-name>springDispatcherServlet</servlet-name> 25 <url-pattern>/</url-pattern> 26 </servlet-mapping> 27 28 <!-- 配置HiddenHttpMethodFilter :可以把post請求轉為delete or put請求 --> 29 30 <filter> 31 <filter-name>HiddenHttpMethodFilter</filter-name> 32 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 33 </filter> 34 <filter-mapping> 35 <filter-name>HiddenHttpMethodFilter</filter-name> 36 <url-pattern>/*</url-pattern> 37 </filter-mapping> 38 39 </web-app>View Code
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestMethod; 7 8 @RequestMapping("/springmvc") 9 @Controller 10 public class RequestMappingTest { 11 private static final String SUCCESS = "success"; 12 13 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT) 14 public String testRestput(@PathVariable("id") Integer id) { 15 System.out.println("testRest-put:" + id); 16 return SUCCESS; 17 } 18 19 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE) 20 public String testRestDelete(@PathVariable("id") Integer id) { 21 System.out.println("testRest-delete:" + id); 22 return SUCCESS; 23 } 24 25 @RequestMapping(value = "/testRest", method = RequestMethod.POST) 26 public String testRestPost() { 27 System.out.println("testRest post"); 28 return SUCCESS; 29 } 30 31 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET) 32 public String testRestGet(@PathVariable("id") Integer id) { 33 System.out.println("testRest-get:" + id); 34 return SUCCESS; 35 } 36 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testRest/1">test rest get</a> 11 <br> 12 <form action="/springmvc/testRest" method="POST"> 13 <input type="submit" value="test rest post"> 14 </form> 15 <form action="/springmvc/testRest/1" method="POST"> 16 <input type="hidden" name="_method" value="DELETE"> <input 17 type="submit" value="test rest delete"> 18 </form> 19 <form action="/springmvc/testRest/1" method="POST"> 20 <input type="hidden" name="_method" value="PUT"> <input 21 type="submit" value="test rest put"> 22 </form> 23 </body> 24 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
執行結果:
index.jsp執行效果如下圖;
點選test rest get 跳轉到success頁面,同時控制檯列印testRest-get:1;
點選test rest post跳轉到success頁面,同時控制檯列印testRest post;
點選test rest delete跳轉到success頁面,同時控制檯列印testRest-delete:1
點選test rest put跳轉到success頁面,同時控制檯列印testRest-put:1;
繫結引數註解
使用@RequestParam繫結請求引數值:
在方法入參處使用@RequestParam 可以把請求引數傳遞給請求方法;
- value:表示請求引數的引數名
- required:是否必須,預設為true,請求引數中必須包含對應的引數,若不存在,將丟擲異常;
- defaultvalue :引數預設值
http://localhost:8080/springmvc/tesRestParam?username=%E6%9D%8E%E7%A7%80%E6%98%8E&age=12中的username必須和@RequestParam(value = "username") String username中的@RequestParam(value="username")的一樣;和String username 可以一樣也可以不一樣;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestParam; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * @RequestParam來對映請求引數 value:請求引數名 required :是否必須 defaultvalue :引數預設值 14 * @return 15 */ 16 @RequestMapping("/tesRestParam") 17 public String tesRestParam(@RequestParam(value = "username") String username, 18 @RequestParam(value = "age", required = false, defaultValue = "0") int age) { 19 System.out.println("tesRestParam:username" + username + ".aget:" + age); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/tesRestParam?username=李秀明&age=12">tesRestParam_username&age</a> 11 <br> 12 <a href="/springmvc/tesRestParam?username=李秀明">tesRestParam_username</a> 13 </body> 14 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp 執行如下圖,點選tesRestParam_username&age 跳轉到success,且控制檯列印:tesRestParam:username李秀明.aget:12;點選tesRestParam_username 跳轉到successtesRestParam:username李秀明.aget:0
@RequestHeader繫結請求報頭屬性值
請求頭包含了若干個屬性,伺服器可據此貨值客戶端的資訊。通過@RequestHeader可將請求頭中的屬性值繫結到處理方法的入參中
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestHeader; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * 用來對映請求頭資訊;用法同@RequestParam 14 * 15 * @return 16 */ 17 @RequestMapping("/tesRestHeader") 18 public String tesRestHeader(@RequestHeader(value = "Accept-Language") String al) { 19 System.out.println("tesRestHeader" + al); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/tesRestHeader">tesRestHeader</a> 11 <br> 12 </body> 13 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果: 點選testRestHeader 跳轉到success頁面,且控制檯列印:tesRestHeaderzh-CN,zh;q=0.9
@CookieValue繫結請求報頭屬性值
通過@CookieValue可讓處理方法入參繫結某個Cookie值;用法同@RequestParam
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.CookieValue; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * @CookieValue對映一個cookie值;用法同@RequestParam 14 * 15 * @return 16 */ 17 @RequestMapping("/testCookieValue") 18 public String testCookieValue(@CookieValue(value = "JSESSIONID") String JSESSIONID) { 19 System.out.println("testCookieValue" + JSESSIONID); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testCookieValue">testCookieValue</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp執行結果如下圖;點選testCookieValue跳轉到success頁面,且控制檯列印testCookieValue6458E41FB8EEF62E6A52F7612D1936D7
使用POJO物件繫結請求引數值;
springMVC 會按照請求引數名和POJO屬性名進行自動匹配,自動為該物件填充屬性。支援級聯屬性。如dept.deptId、dept.address.tel。。。
新增兩個實體類User.java 和 address.java
User.java
1 package entity; 2 3 public class User { 4 private String userName; 5 private int age; 6 private Address address; 7 8 public String getUserName() { 9 return userName; 10 } 11 12 public void setUserName(String userName) { 13 this.userName = userName; 14 } 15 16 public int getAge() { 17 return age; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public Address getAddress() { 25 return address; 26 } 27 28 public void setAddress(Address address) { 29 this.address = address; 30 } 31 32 @Override 33 public String toString() { 34 return "User [userName=" + userName + ", age=" + age + ", address=" + address + "]"; 35 } 36 37 }View Code
address.java
1 package entity; 2 3 public class Address { 4 private String province; 5 private String city; 6 7 public String getProvince() { 8 return province; 9 } 10 11 public void setProvince(String province) { 12 this.province = province; 13 } 14 15 public String getCity() { 16 return city; 17 } 18 19 public void setCity(String city) { 20 this.city = city; 21 } 22 23 @Override 24 public String toString() { 25 return "Address [province=" + province + ", city=" + city + "]"; 26 } 27 28 }View Code
web.xml新增編碼配置,防止form表單提交 控制檯列印亂碼:
該段程式碼配置在web.xml其他過濾器前面,否則無效;
參考解決方式:https://www.cnblogs.com/lixiuming521125/p/14697014.html#_label4
1 <filter> 2 <filter-name>CharacterEncodingFilter</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>utf-8</param-value> 7 </init-param> 8 </filter> 9 <filter-mapping> 10 <filter-name>CharacterEncodingFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 </filter-mapping>
完整內容:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <display-name>HelloWorld</display-name> 7 <filter> 8 <filter-name>CharacterEncodingFilter</filter-name> 9 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 10 <init-param> 11 <param-name>encoding</param-name> 12 <param-value>utf-8</param-value> 13 </init-param> 14 </filter> 15 <filter-mapping> 16 <filter-name>CharacterEncodingFilter</filter-name> 17 <url-pattern>/*</url-pattern> 18 </filter-mapping> 19 <!-- 配置DispatcherServlet(快捷鍵 alt +/) --> 20 <servlet> 21 <servlet-name>springDispatcherServlet</servlet-name> 22 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 23 <!-- 配置DispatcherServletd 一個初始化引數:配置springmvc配置檔案的位置和名稱 --> 24 <!-- 實際上也可以不通過 contextConfigLocation 來配置Springmvc的配置檔案,而是用預設的 即預設的配置檔案為 25 /WEB-INF/<servlet-name>-servlet.xml 本專案預設位置配置檔案即為: /WEB-INF/springDispatcherServlet-servlet.xml --> 26 <init-param> 27 <param-name>contextConfigLocation</param-name> 28 <param-value>classpath:spring.xml</param-value> 29 </init-param> 30 <!-- 表示springDispatcherServlet在載入的時候被建立 --> 31 <load-on-startup>1</load-on-startup> 32 </servlet> 33 34 <!-- Map all requests to the DispatcherServlet for handling --> 35 <servlet-mapping> 36 <servlet-name>springDispatcherServlet</servlet-name> 37 <url-pattern>/</url-pattern> 38 </servlet-mapping> 39 40 <!-- 配置HiddenHttpMethodFilter :可以把post請求轉為delete or put請求 --> 41 42 <filter> 43 <filter-name>HiddenHttpMethodFilter</filter-name> 44 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 45 </filter> 46 <filter-mapping> 47 <filter-name>HiddenHttpMethodFilter</filter-name> 48 <url-pattern>/*</url-pattern> 49 </filter-mapping> 50 51 </web-app>View Code
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 import entity.User; 7 8 @RequestMapping("/springmvc") 9 @Controller 10 public class RequestMappingTest { 11 private static final String SUCCESS = "success"; 12 13 @RequestMapping("/testpojo") 14 public String testpojo(User user) { 15 System.out.println("testpojo" + user); 16 return SUCCESS; 17 } 18 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="/springmvc/testpojo" method="POST"> 11 使用者名稱:<input type="text" name="userName" /> <br> 12 年齡:<input type="text" name="age" /> <br> 13 城市:<input type="text"name="address.city" /> <br> 14 省份:<input type="text" name="address.province" /> <br> 15 <input type="submit" value='提交'> 16 </form> 17 </body> 18 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp 的執行結果如下圖,填寫下面資訊,點選提交,跳轉到 success頁面,且控制檯列印:
testpojoUser [userName=李秀明, age=18, address=Address [province=浙江, city=嘉興]]
servlet 原生的API作為目標方法的引數
具體支援以下型別
- HttpServletRequest,
- HttpServletResponse,
- Writer,
- java.security.Principal,
- Locale
- InputStream,
- OutputStream,
- Reader,
- Writer
RequestMappingTest:
1 package handler; 2 3 import java.io.IOException; 4 import java.io.Writer; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.stereotype.Controller; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 12 @RequestMapping("/springmvc") 13 @Controller 14 public class RequestMappingTest { 15 16 @RequestMapping("/testServletAPI") 17 public void testServletAPI(HttpServletRequest request, HttpServletResponse response, Writer out) 18 throws IOException { 19 out.write("hello spring"); 20 } 21 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testServletAPI">testServletAPI</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>View Code
執行結果:
index.jsp執行效果如下;點選testServletAPI 會顯示hello spring ;