springmvc(3)註解
有疑問可以參考博主其他關於spring mvc的博文
此時直接進行程式碼的實現
一般的步驟:
-加入jar包
-配置DispatcherServlet
-加入Spring MVC配置檔案
-編寫請求的處理器
-檢視
建立web工程:
加入jar包
web.xml檔案
<!-- 配置DispatcherServlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化引數 --> <!-- 配置 DispatcherServlet 的一個初始化引數: 配置 SpringMVC 配置檔案的位置和名稱 --> <!-- 實際上也可以不通過 contextConfigLocation 來配置 SpringMVC 的配置檔案, 而使用預設的. 預設的配置檔案為: /WEB-INF/<servlet-name>-servlet.xml 簡單的列子:在WEB-INF資料夾下springDispatcherServlet-servlet.xml,init就不需要在配置了 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
springmvc.xml以及所需要的類
springmvc.xml
<!-- 配置自動掃描的包 --> <context:component-scan base-package="com.MrChengs.A"></context:component-scan> <!-- 配置檢視解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
HelloWord.java
//自動掃描 @Controller public class HelloWord { //返回值通過檢視解析器解析為實際的物理邏輯檢視,InternalResourceViewResolver解析器 //<property name="prefix" value="/WEB-INF/views/"></property> //<property name="suffix" value=".jsp"></property> //通過字首prefix + 返回值+ 字尾 //==/WEB-INF/views/+ success + .jsp //使用註解來對映請求url @RequestMapping("/helloword") public String say(){ System.out.println("hello"); return "success"; } }
這裡說明需要在路徑下建立相關的 檔案以及路徑:
success.jsp
主要用於成功後的顯示
<body> <h4>success</h4> </body>
在index.jsp
注意路徑在href裡面
<body> <a href="helloword">helloword</a> </body>
得到:注意看請求的url
@RequestMapping
->Spring MVC 使用@RequestMapping註解為控制器指定可以處理哪些URL請求
->在控制器的 類定義及方法 出都可以標註
-->類定義處:提供初步的請求對映資訊。相對於WEB應用的根目錄
-->方法處:提供進一步的細分對映資訊,相對於類定義處的URL
若類定義處未標註@RequestMapping,則方法處標記的URL相對於WEB應用的根目錄
-->DispatcherServlet截獲請求後,就通過控制器上 @RequestMapping 提供的對映資訊確定請求對應的方法
測試在類定義附加方法處
TestRequestMapping.java
此時的路徑是:類定義+方法
@Controller @RequestMapping("/springmvc") public class TestRequestMapping { @RequestMapping("/RequestMapping") public String RequestMapping(){ System.out.println("RequestMapping"); return "success"; } }
在index,jsp中:
<a href="springmvc/RequestMapping">testMethod</a>
在執行之後點選超連結,控制檯會顯示,主要看路徑:
具體可看圖的解釋:
對映請求引數、請求方法或請求頭
->@RequestMapping 除了可以使用 請求 URL 對映請求外,
還可以使用請求方法、請求引數及請求頭對映請求
->@RequestMapping 的 value、method、params 及 heads
分別表示 請求 URL、請求方法、請求引數及請求頭的對映條
件 ,他們之間是與的關係,聯合使用多個條件可讓請求對映
更加精確化
-> params 和 headers 支援簡單的表示式:
– -param1: 表示請求必須包含名為 param1 的請求引數
– -!param1: 表示請求不能包含名為 param1 的請求引數
– -param1 != value1: 表示請求包含名為 param1 的請求引數,但其值
不能為 value1
– -{“param1=value1”, “param2”}: 請求必須包含名為 param1 和param2
的兩個請求引數,且 param1 引數的值必須為 value1
method:
TestRequestMapping.java
可以為post,get......
@RequestMapping(value="/RequestMethod",method=org.springframework.web.bind.annotation.RequestMethod.POST) public String RequestMethod(){ System.out.println("RequestMethod"); return "success"; }
index.jsp中:
<form action="springmvc/RequestMethod" method="post"> <input type="submit" value="submit"> </form>
點選執行之後的按鈕:
如果此時強制使用get會報錯
params
TestRequestMapping.java
@RequestMapping(value="/paramsAndHeaders", params={"user","age!=20"}) public String ParamesHeaders(){ return "success"; }
index.jsp
<a href="springmvc/paramsAndHeaders">paramsAndHeaders</a>
此時user屬性不寫或者age=20,都會報404錯誤
header:
可以使用params和header更加精確的對映請求,
params和headers支援加單的表示式
使用 @RequestMapping 對映請求
Ant 風格資源地址支援 3 種匹配符:
– ?:匹配檔名中的一個字元
– *:匹配檔名中的任意字元
– **:** 匹配多層路徑
@RequestMapping 還支援 Ant 風格的 URL:
/user/*/createUser: 匹配
/user/aaa/createUser、/user/bbb/createUser 等 URL
/user/**/createUser: 匹配
/user/createUser、/user/aaa/bbb/createUser 等 URL
/user/createUserer: 匹配
/user/createUseraa、/user/createUserbb 等 URL
簡單的小例項:
TestRequestMapping.java
@RequestMapping("/antpath/*/ant") public String AntPath(){ return "success"; }
index.jsp:
<a href="springmvc/antpath/mvcmmc/ant">Ant</a>
@PathVariable 對映 URL 繫結的佔位符
帶佔位符的 URL 是 Spring3.0 新增的功能,該功能在SpringMVC 向 REST 目標挺進發展過程中具有里程碑的意義
通過 @PathVariable 可以將 URL 中佔位符引數繫結到控制器處理方法的入參中:URL 中的 {xxx} 佔位符 可以通過
@PathVariable("xxx") 繫結到操作方法的入參
TestRequestMapping.java
@RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable(value="id") int id){ System.out.println("testPathVariable:" + id); return "success"; }
index.jsp
<a href="springmvc/testPathVariable/20">testPathVariable</a>
REST
REST:即 Representational State Transfer。(資源)表現層狀態轉化。是目前
最流行的一種網際網路軟體架構。它結構清晰、符合標準、易於理解、擴充套件方便,
所以正得到越來越多網站的採用
資源(Resources):網路上的一個實體,或者說是網路上的一個具體資訊。它
可以是一段文字、一張圖片、一首歌曲、一種服務,總之就是一個具體的存在。
可以用一個URI(統一資源定位符)指向它,每種資源對應一個特定的 URI 。要
獲取這個資源,訪問它的URI就可以,因此 URI 即為每一個資源的獨一無二的識
別符。
表現層(Representation):把資源具體呈現出來的形式,叫做它的表現層
(Representation)。比如,文字可以用 txt 格式表現,也可以用 HTML 格
式、XML 格式、JSON 格式表現,甚至可以採用二進位制格式。
狀態轉化(State Transfer):每發出一個請求,就代表了客戶端和伺服器的一
次互動過程。HTTP協議,是一個無狀態協議,即所有的狀態都儲存在伺服器
端。因此,如果客戶端想要操作伺服器,必須通過某種手段,讓伺服器端發生“
狀態轉化”(State Transfer)。而這種轉化是建立在表現層之上的,所以就是 “
表現層狀態轉化”
具體說,就是 HTTP 協議裡面,四個表示操作方式的動
詞: GET、POST、PUT、DELETE 。它們分別對應四種基本操作:GET 用來獲
取資源,POST 用來新建資源,PUT 用來更新資源,DELETE 用來刪除資
示例:
– /order/1 HTTP GET :得到 id = 1 的 order
– /order/1 HTTP DELETE:刪除 id = 1的 order
– /order/1 HTTP PUT:更新id = 1的 order
– /order HTTP POST:新增 order
• HiddenHttpMethodFilter:瀏覽器 form 表單只支援 GET
與 POST 請求,而DELETE、PUT 等 method 並不支
持,Spring3.0 添加了一個過濾器,可以將這些請求轉換
為標準的 http 方法,使得支援 GET、POST、PUT 與
DELETE 請求。
需要在web.xml配置:
<!-- 配置org.springframework.web.filter.HiddenHttpMethodFilter.class --> <!-- 可以把POST請求轉為delete/post --> <filter> <filter-name>filter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
java類中:
@RequestMapping(value="/test/{id}",method=org.springframework.web.bind.annotation.RequestMethod.GET) public String testGet(@PathVariable(value="id") int id){ System.out.println("GET:" + id); return "success"; } @RequestMapping(value="/test",method=org.springframework.web.bind.annotation.RequestMethod.POST) public String testPOST(){ System.out.println("POST:"); return "success"; } @RequestMapping(value="/test/{id}",method=org.springframework.web.bind.annotation.RequestMethod.DELETE) public String testDelete(@PathVariable(value="id") int id){ System.out.println("DELETE:" + id); return "success"; } @RequestMapping(value="/test/{id}",method=org.springframework.web.bind.annotation.RequestMethod.PUT) public String testPUT(@PathVariable(value="id") int id){ System.out.println("PUT:" + id); return "success"; }
index.jsp
<a href="springmvc/test/1">GET</a> <br> <form action="springmvc/test" method="post"> <input type="submit" value="POST"> </form> <br> <form action="springmvc/test/1" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" value="DELETE"> </form> <br> <form action="springmvc/test/1" method="post"> <input type="hidden" name="_method" value="PUT"> <input type="submit" value="PUT"> </form>
對映請求引數 & 請求引數
請求處理方法簽名
Spring MVC 通 過分析處理方法的簽名 ,將 HTTP 請求信
息繫結到處理方法的相應 人蔘 中。
Spring MVC 對控制器處理方法簽名的限制是很寬鬆的,
幾乎可以按喜歡的任何方式對方法進行簽名。
必要時可以對方法及方法入參標註相應的註解(
@PathVariable@RequestParam、@RequestHeader 等)、Spring
MVC 框架會將 HTTP 請求的資訊繫結到相應的方法入參
中,並根據方法的返回值型別做出相應的後續處理
使用 @RequestParam 繫結請求引數值
在處理方法入參處使用 @RequestParam 可以把請求引數傳遞給請求方法
– --- value :引數名
– --- required :是否必須。預設為 true, 表示請求引數中必須包含對應的引數,若不存在,將丟擲異常
TestRequestMapping.java
@RequestMapping("/testRequestParam") public String testRequestParam(@RequestParam(value="username",required=false) String username, @RequestParam(value="age") int age){ System.out.println("username:" + username + "--age:" + age); return "success"; }
index.jsp
<a href="springmvc/testRequestParam?username=MrChang&age=22">testRequestParam</a>
@RequestHeader 繫結請求報頭的屬性值
請求頭包含了若干個屬性,伺服器可據此獲知客戶端的信
息,通過 @RequestHeader 即可將請求頭中的屬性值綁
定到處理方法的入參中
TestRequestMapping.java
@RequestMapping("/RequestHeader") public String testRequestHeader(@RequestHeader(value="Accept")String l){ System.out.println(l); return "success"; }
index.jsp
<a href="springmvc/RequestHeader">RequestHeader</a>
使用 POJO 物件繫結請求引數值
Spring MVC 會按請求引數名和 POJO 屬性名進行自動匹
配,自動為該物件填充屬性值。支援 級聯屬性 。
如:dept.deptId、dept.address.tel 等
TestRequestMapping.java
@RequestMapping("/testpojo") public String testtestpojo(User user){ System.out.println(user); return "success"; }
User.java
public class User { private String username; private String password; private String email; private Address address; }
Address.java
public class Address { private String city; }
index.java
<form action="springmvc/testpojo" method="post"> username:<input type="text" name="username"> <br> password:<input type="password" name="password"> <br> email:<input type="text" name="email"> <br> city:<input type="text" name="address.city"> <input type="submit" value="submit"> </form>
使用 Servlet API 作為
TestRequestMapping.java
@RequestMapping("/testServletAPI") public String testServletAPI(HttpServletRequest request, HttpServletResponse response){ System.out.println("request:" + request + "-response:" + response); return "success"; }
<a href="springmvc/testServletAPI">testServletAPI</a>
request:org.apache.catalina.connector.RequestFacade@7a434d60- response:org.apache.catalina.connector.ResponseFacade@addea0e