目錄
一、RequestMapping 注解
1、使用說明
2、使用示例
二、RequestParam注解
1、使用說明
2、使用示例
三、RequestBody注解
1、使用說明
2、使用示例
四、PathVaribale注解
1、使用說明
2、使用示例
3、REST 風格 URL
(1)什麼是 rest
(2)restful 的優點
(3)restful 的特性
(4)restful 的示例:
4、基于 HiddentHttpMethodFilter 的示例
五、RequestHeader注解
1、使用說明
2、使用示例
六、CookieValue注解
1、使用說明
2、使用示例
七、SessionAttribute注解
1、使用說明
2、使用示例
一、RequestMapping 注解
1、使用說明
(1)源碼:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
}
(2)作用: 用于建立請求 URL 和處理請求方法之間的對應關系。
(3)出現位置:
- 類上:
請求 URL 的第一級通路目錄。此處不寫的話,就相當于應用的根目錄。寫的話需要以 / 開頭。 它出現的目的是為了使我們的 URL可以按照子產品化管理:
例如:
賬戶子產品: /account/add /account/update /account/delete ...
訂單子產品: /order/add /order/update /order/delete
紅色的部分就是把 RequsetMapping 寫在類上,使我們的 URL 更加精細。
- 方法上:
請求 URL 的第二級通路目錄。
(4)屬性:
value:用于指定請求的 URL。它和 path 屬性的作用是一樣的。
method:用于指定請求的方式。
params:用于指定限制請求參數的條件。它支援簡單的表達式。要求請求參數的 key 和 value 必須和配置的一模一樣。 例如:params = {"moeny!=100"},表示請求參數中 money 不能是 100。
headers:用于指定限制請求消息頭的條件。 注意: 以上四個屬性隻要出現 2 個或以上時,他們的關系是與的關系。
2、使用示例
(1)class 屬性的示例
/**
* RequestMapping 注解出現的位置
* @Version 1.0
*/
@Controller("accountController")
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount")
public String findAccount(){
System.out.println("查詢了賬戶。。。。");
return "success";
}
}
jsp 中的代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>requestmapping 的使用</title>
</head>
<body>
<!-- 第一種通路方式 -->
<a href="${pageContext.request.contextPath}/account/findAccount" target="_blank" rel="external nofollow" >查詢 賬戶</a> <br/>
<!--第二種通路方式 -->
<a href="account/findAccount" target="_blank" rel="external nofollow" >查詢賬戶</a>
</body>
</html>
注意:
當我們使用此種方式配置時,在 jsp 中第二種寫法時,不要在通路 URL 前面加 / ,否則無法找到資源。
(2)method 屬性的示例
控制器代碼:
/**
* 儲存賬戶
* @return
*/
@RequestMapping(value="/saveAccount",method=RequestMethod.POST)
public String saveAccount() {
System.out.println("儲存了賬戶");
return "success";
}
jsp 代碼:
<!-- 請求方式的示例 -->
<a href="account/saveAccount" target="_blank" rel="external nofollow" >儲存賬戶,get 請求</a>
<br/>
<form action="account/saveAccount" method="post">
<input type="submit" value="儲存賬戶,post 請求">
</form>
注意: 當使用 get 請求時,提示錯誤資訊是 405,資訊是方法不支援 get 方式請求
(3)params 屬性的示例:
控制器的代碼:
/**
* 删除賬戶
* @return
*/
@RequestMapping(value="/removeAccount",params= {"accountName","money=100"})
public String removeAccount() {
System.out.println("删除了賬戶");
return "success";
}
jsp 中的代碼:
<!-- 請求參數的示例 -->
<a href="account/removeAccount?accountName=aaa&money=100" target="_blank" rel="external nofollow" >删除賬戶, 金額 100</a>
<br/>
<a href="account/removeAccount?accountName=aaa&money=150" target="_blank" rel="external nofollow" >删除賬戶, 金額 150</a>
注意: 當我們點選第一個超連結時,可以通路成功。 當我們點選第二個超連結時,無法通路。因為 params= {"accountName","money=100"} ,限制了 money=100 的條件
二、RequestParam注解
1、使用說明
作用: 把請求中指定名稱的參數給控制器中的形參指派。
屬性: value:請求參數中的名稱。 required:請求參數中是否必須提供此參數。
預設值:true。表示必須提供,如果不提供将報錯。
2、使用示例
jsp
<!-- requestParams 注解的使用 -->
<a href="springmvc/useRequestParam?name=test" target="_blank" rel="external nofollow" >requestParam 注解</a>
控制器中的代碼:
/**
* requestParams 注解的使用
*
* @param username
* @return
*/
@RequestMapping("/useRequestParam")
public String useRequestParam(@RequestParam("name") String username, @RequestParam(value = "age", required = false) Integer age) {
System.out.println(username + "," + age);
return "success";
}
運作結果:
三、RequestBody注解
1、使用說明
作用: 用于擷取請求體内容。直接使用得到是 key=value&key=value...結構的資料。 get 請求方式不适用。
屬性: required:是否必須有請求體。預設值是:true。當取值為 true 時,get 請求方式會報錯。如果取值為 false,get 請求得到是 null。
2、使用示例
post 請求 jsp 代碼:
<!-- request body 注解 -->
<form action="springmvc/useRequestBody" method="post">
使用者名稱:<input type="text" name="username" ><br/>
使用者密碼:<input type="password" name="password" ><br/>
使用者年齡:<input type="text" name="age" ><br/>
<input type="submit" value="儲存">
</form>
get 請求 jsp 代碼:
<a href="springmvc/useRequestBody?body=test" target="_blank" rel="external nofollow" >requestBody 注解 get 請求</a>
控制器代碼:
/**
* RequestBody 注解
* @return
*/
@RequestMapping("/useRequestBody")
public String useRequestBody(@RequestBody(required=false) String body){
System.out.println(body);
return "success";
}
post 請求運作結果:
get 請求運作結果:
四、PathVaribale注解
1、使用說明
作用: 用于綁定 url 中的占位符。例如:請求 url 中 /delete/{id},這個{id}就是 url 占位符。 url 支援占位符是 spring3.0 之後加入的。是 springmvc 支援 rest 風格 URL 的一個重要标志。
屬性: value:用于指定 url 中占位符名稱。 required:是否必須提供占位符。
2、使用示例
jsp代碼:
<!-- PathVariable 注解 -->
<a href="springmvc/usePathVariable/100" target="_blank" rel="external nofollow" >pathVariable 注解</a>
控制器代碼:
/**
* PathVariable 注解
*
* @return
*/
@RequestMapping("/usePathVariable/{id}")
public String usePathVariable(@PathVariable("id") Integer id) {
System.out.println(id);
return "success";
}
運作結果:
3、REST 風格 URL
(1)什麼是 rest
REST(英文:Representational State Transfer,簡稱 REST)描述了一個架構樣式的網絡系統,比如 web 應用程式。它首次出現在 2000 年 Roy Fielding 的博士論文中,他是 HTTP 規範的主要編寫者之一。在目前主流的三種 Web 服務互動方案中,REST 相比于 SOAP(Simple Object Access protocol,簡單對象通路協定)以及 XML-RPC 更加簡單明了,無論是對 URL 的處理還是對 Payload 的編碼,REST 都傾向于用更加簡單輕量的方法設計和實作。值得注意的是 REST 并沒有一個明确的标準,而更像是一種設計的風格。它本身并沒有什麼實用性,其核心價值在于如何設計出符合 REST 風格的網絡接口。
(2)restful 的優點
它結構清晰、符合标準、易于了解、擴充友善,是以正得到越來越多網站的采用。
(3)restful 的特性
資源(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 用來删除資源
(4)restful 的示例:
- /account/1 HTTP GET : 得到 id = 1 的 account
- /account/1 HTTP DELETE: 删除 id = 1 的 account
- /account/1 HTTP PUT: 更新 id = 1 的 account
- /account HTTP POST: 新增 account
4、基于 HiddentHttpMethodFilter 的示例
作用: 由于浏覽器 form 表單隻支援 GET 與 POST 請求,而 DELETE、PUT 等 method 并不支援,Spring3.0 添加了一個過濾器,可以将浏覽器請求改為指定的請求方式,發送給我們的控制器方法,使得支援 GET、POST、PUT 與 DELETE 請求。
使用方法:
- 第一步:在 web.xml 中配置該過濾器。 HiddenHttpMethodFilter
- 第二步:請求方式必須使用 post 請求。
- 第三步:按照要求提供 _method 請求參數,該參數的取值就是我們需要的請求方式。
web.xml 中配置過濾器
<!--配置HiddenHttpMethodFilter-->
<!--
配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉為 DELETE 或 PUT 請求
-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
jsp中示例代碼:
<!-- 儲存 -->
<form action="account/testRestPOST" method="post">
使用者名稱:<input type="text" name="username"><br/>
<input type="hidden" name="_method" value="POST">
<input type="submit" value="儲存">
</form>
<hr/>
<!-- 更新 -->
<form action="account/testRestPUT/1" method="post">
使用者名稱:<input type="text" name="username"><br/>
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="更新"></form>
<hr/>
<!-- 删除 -->
<form action="account/testRestDELETE/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="删除">
</form>
<hr/>
<!-- 查詢一個 -->
<form action="account/testRestGET/1" method="post">
<input type="hidden" name="_method" value="GET">
<input type="submit" value="查詢">
</form>
控制器中示例代碼
/**
* post 請求:儲存
*
* @return
*/
@RequestMapping(value = "/testRestPOST", method = RequestMethod.POST)
public String testRestfulURLPOST(String username) {
System.out.println("rest post , " + username);
return "success";
}
/**
* put 請求:更新
*
* @return
*/
@RequestMapping(value = "/testRestPUT/{id}", method = RequestMethod.PUT)
public String testRestfulURLPUT(@PathVariable("id") Integer id, String username) {
System.out.println("rest put , " + id + "," + username);
return "success";
}
/**
* post 請求:删除
*
* @return
*/
@RequestMapping(value = "/testRestDELETE/{id}", method = RequestMethod.DELETE)
public String testRestfulURLDELETE(@PathVariable("id") Integer id) {
System.out.println("rest delete , " + id);
return "success";
}
/**
* post 請求:查詢
*
* @return
*/
@RequestMapping(value = "/testRestGET/{id}", method = RequestMethod.GET)
public String testRestfulURLGET(@PathVariable("id") Integer id) {
System.out.println("rest get , " + id);
return "success";
}
執行結果
五、RequestHeader注解
1、使用說明
作用: 用于擷取請求消息頭。
屬性: value:提供消息頭名稱 required:是否必須有此消息頭
- 注:在實際開發中一般不怎麼用。
2、使用示例
jsp中代碼
<!-- RequestHeader 注解 -->
<a href="springmvc/useRequestHeader" target="_blank" rel="external nofollow" >擷取請求消息頭</a>
控制器中代碼:
/**
* RequestHeader 注解 * @param user * @return
*/
@RequestMapping("/useRequestHeader")
public String useRequestHeader(@RequestHeader(value = "Accept-Encoding", required = false) String requestHeader) {
System.out.println(requestHeader);
return "success";
}
執行結果:
六、CookieValue注解
1、使用說明
作用: 用于把指定 cookie 名稱的值傳入控制器方法參數。
屬性: value:指定 cookie 的名稱。 required:是否必須有此 cookie。
2、使用示例
jsp中代碼:
<!-- CookieValue 注解 -->
<a href="springmvc/useCookieValue" target="_blank" rel="external nofollow" >綁定 cookie 的值</a>
控制器中的代碼:
/**
* Cookie 注解注解 * @param user * @return
*/
@RequestMapping("/useCookieValue")
public String useCookieValue(@CookieValue(value = "JSESSIONID", required = false) String cookieValue) {
System.out.println(cookieValue);
return "success";
}
執行結果:
七、SessionAttribute注解
1、使用說明
作用: 用于多次執行控制器方法間的參數共享。
屬性: value:用于指定存入的屬性名稱 type:用于指定存入的資料類型。
2、使用示例
jsp中的代碼:
<!-- SessionAttribute 注解的使用 -->
<a href="account/testPut" target="_blank" rel="external nofollow" >存入 SessionAttribute</a>
<hr/>
<a href="account/testGet" target="_blank" rel="external nofollow" >取出 SessionAttribute</a>
<hr/>
<a href="account/testClean" target="_blank" rel="external nofollow" >清除 SessionAttribute</a>
控制器中的代碼:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
@Controller
@RequestMapping("/account")
@SessionAttributes(value = {"username", "password"}, types = {Integer.class})
public class AccountController {
/**
* 把資料存入 SessionAttribute
*
* @param model
* @return Model 是 spring 提供的一個接口,該接口有一個實作類 ExtendedModelMap
* 該類繼承了 ModelMap,而 ModelMap 就是 LinkedHashMap 子類
*/
@RequestMapping("/testPut")
public String testPut(Model model) {
model.addAttribute("username", "泰斯特");
model.addAttribute("password", "123456");
model.addAttribute("age", 31);
//跳轉之前将資料儲存到 username、password 和 age 中,因為注解 @SessionAttribute 中有這幾個參數
System.out.println("testPut - 存入了資料");
return "success";
}
@RequestMapping("/testGet")
public String testGet(ModelMap model) {
System.out.println("testGet - 取資料 - " + model.get("username") + ";" + model.get("password") + ";" + model.get("age"));
return "success";
}
@RequestMapping("/testClean")
public String complete(SessionStatus sessionStatus) {
sessionStatus.setComplete();
System.out.println("testClean - 删除了資料");
return "success";
}
}
運作結果: