目錄
一、常用注解
1.1.@RequestMapping
1.2.@RequestParam
1.3.@ModelAttribute
1.4.@SessionAttributes
1.5.@RequestBody
1.6.@RequestHeader
1.7.@PathVariable
1.8.@CookieValue
二、參數(shù)傳遞
2.1.基礎(chǔ)類型+String
2.2.復(fù)雜類型
2.3.@RequestParam
2.4.@PathVariable
2.5.@RequestBody
2.6.@RequestHeader
三、返回值
3.1.void
3.2.String
3.3.String+Model
3.4.ModelAndView
四、頁面跳轉(zhuǎn)
一、常用注解
1.1.@RequestMapping
@RequestMapping注解是一個(gè)用來處理請(qǐng)求地址映射的注解,可用于映射一個(gè)請(qǐng)求或一個(gè)方法,可以用在類或方法上。
-
標(biāo)注在方法上
用于方法上,表示在類的父路徑下追加方法上注解中的地址將會(huì)訪問到該方法
@Controller
public class HelloController {
?
@RequestMapping("/requestTest")
public String requestTest(){
? return "success";
}
}
-
標(biāo)注在類和方法上
用于類上,表示類中的所有響應(yīng)請(qǐng)求的方法都是以該地址作為父路徑。
注意:當(dāng)你在類上添加RequestMapping注解后,如果要請(qǐng)求映射,就意味著請(qǐng)求要先映射到標(biāo)注類的位置,然后再映射到該類的方法上
@Controller
@RequestMapping("/hello")
public class HelloController {
?
@RequestMapping("/requestTest")
public String requestTest(){
? return "success";
}
}
-
參數(shù)列表
參數(shù) | 說明 |
---|---|
value | @RequestMapping 的 value 屬性必須設(shè)值; @RequestMapping 的 value 屬性是通過當(dāng)前請(qǐng)求的請(qǐng)求地址來匹配請(qǐng)求; 從源碼中可以看到value屬性是一個(gè)字符串類型的數(shù)組,因此說明可以將多個(gè)請(qǐng)求映射到一個(gè)方法上,只需要給 value 來指定一個(gè)包含多個(gè)路徑的數(shù)組。 |
method | @RequestMapping的method屬性是通過當(dāng)前請(qǐng)求的請(qǐng)求方式來匹配請(qǐng)求; 瀏覽器向服務(wù)器發(fā)送請(qǐng)求,請(qǐng)求方式有很多GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS、TRACE??梢允褂?method 屬性來約束請(qǐng)求方式。 |
headers | @RequestMapping的headers屬性是通過當(dāng)前請(qǐng)求的請(qǐng)求頭信息來匹配請(qǐng)求; @RequestMapping的headers屬性是一個(gè)字符串類型的數(shù)組,可以通過下面四種表達(dá)是來設(shè)置匹配關(guān)系 例如: “header”:要求請(qǐng)求映射的請(qǐng)求必須為包含 header的請(qǐng)求頭信息 “!header”:要求請(qǐng)求映射的請(qǐng)求必須為不包含 header的請(qǐng)求頭信息 “header=value”:要求請(qǐng)求映射的請(qǐng)求必須為包含 header的請(qǐng)求頭信息,并且header的值必須為value “header!=value”:要求請(qǐng)求映射的請(qǐng)求必須為包含 header的請(qǐng)求頭信息,并且header的值必須不是value |
params | @RequestMapping的params屬性是通過當(dāng)前請(qǐng)求的請(qǐng)求參數(shù)來匹配請(qǐng)求; @RequestMapping的params屬性是一個(gè)字符串類型的數(shù)組,可以通過下面四種表達(dá)是來設(shè)置匹配關(guān)系 例如: “param”:要求請(qǐng)求映射的請(qǐng)求必須為包含 param的請(qǐng)求參數(shù) “!param”:要求請(qǐng)求映射的請(qǐng)求是不能包含param的請(qǐng)求參數(shù) “param=value”:要求請(qǐng)求映射的請(qǐng)求必須包含 param 的請(qǐng)求參數(shù),且 param 參數(shù)的值必須為 value “param!=value”: 要求請(qǐng)求映射的請(qǐng)求是必須包含 param 的請(qǐng)求參數(shù),其值不能為 value。 |
示例一:@RequestMapping的params屬性
@RequestMapping(value = "/test",params = "username")
public String test(){
return "success";
}
注意:我們?cè)O(shè)置了params屬性,就意味著該請(qǐng)求映射的請(qǐng)求必須包含username才能夠請(qǐng)求成功。
示例二:@RequestMapping的headers屬性
@RequestMapping(value = "/test",headers = "Host = localhost:8081")
public String test(){
return "success";
}
注意:如果當(dāng)前請(qǐng)求不滿足headers屬性,此時(shí)頁面就會(huì)顯示404錯(cuò)誤,即資源未找到。
擴(kuò)展:
@GetMapping:處理get方式請(qǐng)求的映射 @PostMapping:處理post方式請(qǐng)求的映射 @PutMapping:處理put方式請(qǐng)求的映射 @DeleteMapping:處理delete方式請(qǐng)求的映射 @GetMapping就相當(dāng)于@RequestMapping(method=RequestMethod.GET),它會(huì)將get映射到特定的方法上。
1.2.@RequestParam
@RequestParam主要用于將請(qǐng)求參數(shù)區(qū)域的數(shù)據(jù)映射到控制層方法的參數(shù)上
參數(shù) | 說明 |
---|---|
value | 請(qǐng)求中傳入?yún)?shù)的名稱,如果不設(shè)置后臺(tái)接口的value值,則會(huì)默認(rèn)為該變量名。 |
required | 該參數(shù)是否為必傳項(xiàng)。默認(rèn)是true,表示請(qǐng)求中一定要傳入對(duì)應(yīng)的參數(shù),否則會(huì)報(bào)404錯(cuò)誤,如果設(shè)置為false時(shí),當(dāng)請(qǐng)求中沒有此參數(shù),將會(huì)默認(rèn)為null,而對(duì)于基本數(shù)據(jù)類型的變量,則必須有值,這時(shí)會(huì)拋出空指針異常。如果允許空值,則接口中變量需要使用包裝類來聲明。 |
defaultValue | 參數(shù)的默認(rèn)值,如果請(qǐng)求中沒有同名的參數(shù)時(shí),該變量默認(rèn)為此值。注意默認(rèn)值可以使用SpEL表達(dá)式,如"#{systemProperties[‘java.vm.version’]}" |
示例:
@RequestMapping("/queryBooks")
public List<Book> queryBooks(
@RequestParam(required = false,defaultValue = "0",value="page") int page,
? ?@RequestParam(required = false,defaultValue = "10",value = "rows") int rows){
? ? ? ?return bookService.queryBooks(page,rows);
}
1.3.@ModelAttribute
@ModelAttribute一個(gè)具有如下三個(gè)作用:
-
綁定請(qǐng)求參數(shù)到命令對(duì)象:放在功能處理方法的入?yún)⑸蠒r(shí),用于將多個(gè)請(qǐng)求參數(shù)綁定到一個(gè)命令對(duì)象,從而簡(jiǎn)化綁定流程,而且自動(dòng)暴露為模型數(shù)據(jù)用于視圖頁面展示時(shí)使用;
-
暴露表單引用對(duì)象為模型數(shù)據(jù):放在處理器的一般方法(非功能處理方法)上時(shí),是為表單準(zhǔn)備要展示的表單引用對(duì)象,如注冊(cè)時(shí)需要選擇的所在城市等,而且在執(zhí)行功能處理方法(@RequestMapping注解的方法)之前,自動(dòng)添加到模型對(duì)象中,用于視圖頁面展示時(shí)使用;
-
暴露@RequestMapping方法返回值為模型數(shù)據(jù):放在功能處理方法的返回值上時(shí),是暴露功能處理方法的返回值為模型數(shù)據(jù),用于視圖頁面展示時(shí)使用。
示例一:綁定請(qǐng)求參數(shù)到命令對(duì)象
如用戶登錄,我們需要捕獲用戶登錄的請(qǐng)求參數(shù)(用戶名、密碼)并封裝為用戶對(duì)象,此時(shí)我們可以使用@ModelAttribute綁定多個(gè)請(qǐng)求參數(shù)到我們的命令對(duì)象。
public String test1(@ModelAttribute("user") UserModel user)
它的作用是將該綁定的命令對(duì)象以“user”為名稱添加到模型對(duì)象中供視圖頁面展示使用。我們此時(shí)可以在視圖頁面使用${user.username}來獲取綁定的命令對(duì)象的屬性。
示例二:暴露表單引用對(duì)象為模型數(shù)據(jù)
@ModelAttribute
public void init(Model model){
model.addAttribute("book",new Book());
}
?
如上代碼會(huì)在執(zhí)行功能處理方法之前執(zhí)行,并將其自動(dòng)添加到模型對(duì)象中。
@RequestMapping("/toBookList")
public String toBookList(){
? ?System.out.println("toBookList");
? ?return "book/bookList";
}
示例三:暴露@RequestMapping方法返回值為模型數(shù)據(jù)
@ModelAttribute注解的返回值會(huì)覆蓋@RequestMapping注解方法中的@ModelAttribute注解的同名命令對(duì)象。
public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)
1.4.@SessionAttributes
在默認(rèn)情況下,當(dāng)ModelMap中的屬性作用域是request級(jí)別時(shí),也就是說,當(dāng)本次請(qǐng)求結(jié)束后,ModelMap中的屬性將銷毀。如果希望在多個(gè)請(qǐng)求中共享ModelMap中的屬性,必須將其屬性轉(zhuǎn)存到session中,這樣ModelMap的屬性才會(huì)被跨請(qǐng)求訪問;
spring允許我們有選擇地指定ModelMap中的哪些屬性需要轉(zhuǎn)存到session中,以便下一個(gè)請(qǐng)求屬對(duì)應(yīng)的ModelMap的屬性列表中還能訪問到這些屬性。
SpringMVC為我們提供這樣一個(gè)注解來實(shí)現(xiàn)上面的場(chǎng)景:@SessionAttributes
:將ModelMap的屬性值共享到session中。
注意:@SessionAttributes注解只能使用在類上,用于在多個(gè)請(qǐng)求之間傳遞參數(shù),類似于Session的Attribute,但不完全一樣,一般來說@SessionAttributes設(shè)置的參數(shù)只用于暫時(shí)的傳遞(存入sessionAttributeStore),而不是長(zhǎng)期的保存,長(zhǎng)期保存的數(shù)據(jù)還是要放到Session中。
有兩種方式將ModelMap中的屬性值共享到session中:
-
使用注解的value屬性:可以通過屬性名指定需要放到會(huì)話中的屬性;
@Controller
@SessionAttributes("user") //將ModelMap中key為user的屬性共享到session中
public class DemoController {
@RequestMapping("/hello") ?
public String hello(ModelMap model) {
//向ModelMap中添加key為user和user1的屬性
? ? ? ?model.addAttribute("user", new User(520, "U love me"));
? ? ? ?model.addAttribute("user1", new User("I love U"));
? ? ? ?return "result";
? }
}
-
使用注解的types屬性:還可以通過模型屬性的對(duì)象類型指定哪些模型屬性需要放到會(huì)話中。
@SessionAttributes(types = {User.class})
@Controller
public class DemoController{
? ?@RequestMapping("/hello")
? ?public String hello(Map<String, Object> map){
? ? ? ?map.put("user1", new User(520, "U love me"));
? ? ? ?return "hello";
? }
}
1.5.@RequestBody
@RequestBody主要用來接收前端傳遞給后端的json字符串中的數(shù)據(jù)的(即請(qǐng)求體中的數(shù)據(jù)的);
GET方式無請(qǐng)求體,所以使用@RequestBody接收數(shù)據(jù)時(shí),前端不能使用GET方式提交數(shù)據(jù),而是用POST方式進(jìn)行提交。在后端的同一個(gè)接收方法里,@RequestBody與@RequestParam()可以同時(shí)使用,@RequestBody最多只能有一個(gè),而@RequestParam()可以有多個(gè)。
簡(jiǎn)言之:
-
一個(gè)請(qǐng)求:只有一個(gè)@RequestBody;
-
一個(gè)請(qǐng)求:可以有多個(gè)@RequestParam。
Content-type: (1)application/x-www-form-urlencoded:@RequestBody不是必須加的 (2)mutipart/form-data:@RequestBody不能處理這種格式 (3)其他格式,比如application/json,application/xml等,必須使用@RequestBody來處理
@RequestMapping("/hello")
public String toHello1(@RequestBody Book book){
? ?log.info(">>>> 使用@RequestBody傳遞JSON格式的參數(shù):{}", JSON.toJSONString(book));
? ?return "index";
}
@RequestBody注解對(duì)應(yīng)的類在將HTTP的輸入流(含請(qǐng)求體)裝配到目標(biāo)類(即:@RequestBody后面的類)時(shí),會(huì)根據(jù)json字符串中的key來匹配對(duì)應(yīng)實(shí)體類的屬性,如果匹配一致且json中的該key對(duì)應(yīng)的值符合(或可轉(zhuǎn)換為)實(shí)體類的對(duì)應(yīng)屬性的類型要求時(shí),會(huì)調(diào)用實(shí)體類的setter方法將值賦給該屬性。
1.6.@RequestHeader
使用 @RequestHeader 注解可以獲取指定的請(qǐng)求頭信息。如果想要獲取所有的請(qǐng)求頭信息,可以使用 Map<String,String>、MultiValueMap<String,String>、HttpHeaders 這三個(gè) Map 中的任何一個(gè)封裝所有請(qǐng)求頭的 name 和 value。
參數(shù)列表
參數(shù) | 說明 |
---|---|
name | name 和 value 互為別名,當(dāng)只有一個(gè)參數(shù)時(shí),可以省略 value,直接("xxx") 就可以了 |
value | name 和 value 互為別名,當(dāng)只有一個(gè)參數(shù)時(shí),可以省略 value,直接("xxx") 就可以了 |
required | 默認(rèn)情況下,如果請(qǐng)求頭中缺少了指定的 name,那么將會(huì)報(bào)錯(cuò)。 如果沒有添加required = false,當(dāng)請(qǐng)求頭中沒有這個(gè)zking請(qǐng)求頭時(shí)就會(huì)報(bào)錯(cuò)。 |
defaultValue | 如果請(qǐng)求頭中缺少了指定的 name ,那么會(huì)報(bào)錯(cuò),可以使用 defaultValue 這個(gè)屬性指定默認(rèn)值,就可以避免報(bào)錯(cuò) ;如果請(qǐng)求頭缺少指定 name ,該屬性設(shè)置的值將會(huì)作為默認(rèn)值,如果該屬性不設(shè)置值,它有自己的默認(rèn)值 DEFAULT_NONE |
示例:
@GetMapping("/headParams")
public Map userInfo(
? ?@RequestHeader(value = "zking",defaultValue = "hello zking") String username,
? ?// 將請(qǐng)求頭中 name=Accept-Encoding 賦值給形參 encoding
? ?@RequestHeader("Accept-Encoding") String encoding,
? ?// 將請(qǐng)求頭中 name=Host 賦值給形參 host
? ?@RequestHeader("Host") String host,
? ?// 將所有請(qǐng)求頭的 name 和 value 封裝到 Map 集合 headsMap 中
? ?@RequestHeader Map<String,String> headsMap) {
? ? ? ?Map map = new HashMap<String, Object>();
? ? ? ?map.put("username",username);
? ? ? ?map.put("Accept-Encoding",encoding);
? ? ? ?map.put("Host",host);
? ? ? ?map.put("headsMap",headsMap);
?
? ? ? ?return map;
}
由于請(qǐng)求頭中不存在 name=zking 這個(gè)信息,所以如果只用 value=zking 會(huì)拋出異常。
解決方案: 1、required 的默認(rèn)值為 true ,也就是請(qǐng)求頭中沒有 name=zking 會(huì)報(bào)錯(cuò),將其值改為 false,即沒有該頭信息也不報(bào)錯(cuò)
@RequestHeader(value = "zking",required = "false") String username
2、不修改 required=true 這個(gè)默認(rèn)值,當(dāng)頭信息中不包含 name=zking ,給它一個(gè)默認(rèn)值 hello zking
@RequestHeader(value = "zking",defaultValue = "hello zking") String username
1.7.@PathVariable
該注解請(qǐng)求URI中的模板變量部分到處理器功能處理方法的方法參數(shù)上的綁定。
即當(dāng)使用@RequestMapping URI template 樣式映射時(shí), 即 someUrl/{paramId}, 這時(shí)的paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數(shù)上。
//@PathVariable可以用來映射URL中的占位符到目標(biāo)方法的參數(shù)中
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id)
{
? ?System.out.println("testPathVariable:"+id);
? ?return SUCCESS;
}
Rest
即 Representational State Transfer。(資源)表現(xiàn)層狀態(tài)轉(zhuǎn)化。是目前最流行的一種互聯(lián)網(wǎng)軟件架構(gòu)。它結(jié)構(gòu)清晰、符合標(biāo)準(zhǔn)、易于理解、擴(kuò)展方便,所以正得到越來越多網(wǎng)站的采用。
-
資源(Resources):網(wǎng)絡(luò)上的一個(gè)實(shí)體,或者說是網(wǎng)絡(luò)上的一個(gè)具體信息。它可以是一段文本、一張圖片、一首歌曲、一種服務(wù),總之就是一個(gè)具體的存在??梢杂靡粋€(gè)URI(統(tǒng)一資源定位符)指向它,每種資源對(duì)應(yīng)一個(gè)特定的 URI 。要獲取這個(gè)資源,訪問它的URI就可以,因此 URI 即為每一個(gè)資源的獨(dú)一無二的識(shí)別符。
-
表現(xiàn)層(Representation):把資源具體呈現(xiàn)出來的形式,叫做它的表現(xiàn)層(Representation)。比如,文本可以用 txt 格式表現(xiàn),也可以用 HTML 格式、XML 格式、JSON 格式表現(xiàn),甚至可以采用二進(jìn)制格式。
-
狀態(tài)轉(zhuǎn)化(State Transfer):每發(fā)出一個(gè)請(qǐng)求,就代表了客戶端和服務(wù)器的一次交互過程。HTTP協(xié)議,是一個(gè)無狀態(tài)協(xié)議,即所有的狀態(tài)都保存在服務(wù)器端。因此,如果客戶端想要操作服務(wù)器,必須通過某種手段,讓服務(wù)器端發(fā)生“狀態(tài)轉(zhuǎn)化”(State Transfer)。而這種轉(zhuǎn)化是建立在表現(xiàn)層之上的,所以就是 “表現(xiàn)層狀態(tài)轉(zhuǎn)化”。具體說,就是 HTTP 協(xié)議里面,四個(gè)表示操作方式的動(dòng)詞:GET、POST、PUT、DELETE。它們分別對(duì)應(yīng)四種基本操作: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
1.8.@CookieValue
@CookieValue注解主要是將請(qǐng)求的Cookie數(shù)據(jù),映射到功能處理方法的參數(shù)上。
參數(shù)列表
參數(shù) | 說明 |
---|---|
value | 綁定的參數(shù)名稱,String類型。 |
required | 是否必須包含value,boolean類型,默認(rèn)為 true,表示請(qǐng)求參數(shù)中必須包含對(duì)應(yīng)的參數(shù);若不存在,將拋出異常。 |
defaultValue | 默認(rèn)值,String類型。當(dāng)沒有傳參時(shí)將使用此值賦值。 |
示例:
@RequestMapping("/testCookieValue")
public Map<String, Object> testCookieValue(
@CookieValue("JSESSIONID") String cookie) {
? ?response.put("cookie", cookie);
? ?return response;
}
二、參數(shù)傳遞
pom.xml
<log4j2.version>2.9.1</log4j2.version>
<log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
<slf4j.version>1.7.13</slf4j.version>
?
<!--4.log日志相關(guān)依賴-->
?
<!-- log4j2日志相關(guān)依賴 -->
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
?
<!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--用于與slf4j保持橋接-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
<scope>runtime</scope>
</dependency>
?
<!--需要使用log4j2的AsyncLogger需要包含disruptor-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${log4j2.disruptor.version}</version>
</dependency>
?
2.1.基礎(chǔ)類型+String
@RequestMapping("/hello1")
? ?public String toHello1(Integer bid,String bname){
? ? ? ?log.info(">>>> 基礎(chǔ)類型+String傳參:{},{}",bid,bname);
? ? ? ?return "index";
? }
2.2.復(fù)雜類型
@RequestMapping("/hello2")
? ?public String toHello2(Book book,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpServletRequest req,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpServletResponse resp,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpSession session){
? ? ? ?System.out.println(book);
? ? ? ?log.info(">>>> HttpServletRequest/HttpServletResponse/HttpSession等等傳參:{}", req.getRequestURI());
? ? ? ?return "index";
? }
2.3.@RequestParam
@RequestMapping("/hello3")
? ?public String toHello3(@RequestParam Integer bid,
? ? ? ? ? ? ? ? ? ? ? ? ? @RequestParam(required = false,value = "price") Integer bookPrice,
? ? ? ? ? ? ? ? ? ? ? ? ? @RequestParam("bookName") String bname){
? ? ? ?log.info(">>>> 使用@RequestParam注解傳遞參數(shù):{},{},{}", bid,bname,bookPrice);
? ? ? ?return "index";
? }
2.4.@PathVariable
@RequestMapping("/hello4/{bid}")
? ?public String toHello4(@PathVariable("bid") Integer bid){
? ? ? ?log.info(">>>> 使用@PathVariable注解傳遞參數(shù):{}", bid);
? ? ? ?return "index";
? }
2.5.@RequestBody
<jackson.version>2.9.3</jackson.version>
<dependency>
? ? <groupId>com.fasterxml.jackson.core</groupId>
? ? <artifactId>jackson-databind</artifactId>
? ? <version>${jackson.version}</version>
? </dependency>
? <dependency>
? ? <groupId>com.fasterxml.jackson.core</groupId>
? ? <artifactId>jackson-core</artifactId>
? ? <version>${jackson.version}</version>
? </dependency>
? <dependency>
? ? <groupId>com.fasterxml.jackson.core</groupId>
? ? <artifactId>jackson-annotations</artifactId>
? ? <version>${jackson.version}</version>
? </dependency>
// ? 能接受json數(shù)據(jù),前提導(dǎo)入了Jackson依賴,沒有導(dǎo)入Jackson依賴的話那進(jìn)不了這個(gè)方法
? ?@RequestMapping("/hello5")
? ?public String toHello5(@RequestBody Map map){
? ? ? ?System.out.println(map);
? ? ? ?return "index";
? }
?
// 不能接受json數(shù)據(jù)
? ?@RequestMapping("/hello6")
? ?public String toHello6(Map map){
? ? ? ?System.out.println(map);
? ? ? ?return "index";
? }
請(qǐng)使用postman或者apipost/eolink等工具發(fā)送請(qǐng)求數(shù)據(jù)。
2.6.@RequestHeader
@RequestMapping("/hello7")
? public String toHello7(Book book, @RequestBody Map map, @RequestHeader("jwt") String jwt){
? ? ? System.out.println(map);
? ? ? System.out.println(book);
? ? ? System.out.println(jwt);
? ? ? return "index";
? }
綜合代碼
package com.zking.controller;
?
import com.zking.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
?
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
?
@Slf4j
@RequestMapping("/demo")
@Controller
public class ParamController {
? @RequestMapping(value="/hello")
? public String hello(){
? ? ? System.out.println("被調(diào)用了。。。。");
? ? ? return "index";
? }
?
? @RequestMapping("/hello1")
? public String toHello1(Integer bid,String bname){
? ? ? log.info(">>>> 基礎(chǔ)類型+String傳參:{},{}",bid,bname);
? ? ? return "index";
? }
?
? @RequestMapping("/hello2")
? public String toHello2(Book book,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpServletRequest req,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpServletResponse resp,
? ? ? ? ? ? ? ? ? ? ? ? ? HttpSession session){
? ? ? System.out.println(book);
? ? ? log.info(">>>> HttpServletRequest/HttpServletResponse/HttpSession等等傳參:{}", req.getRequestURI());
? ? ? return "index";
? }
?
? @RequestMapping("/hello3")
? public String toHello3(@RequestParam Integer bid,
? ? ? ? ? ? ? ? ? ? ? ? ? @RequestParam(required = false,value = "price") Integer bookPrice,
? ? ? ? ? ? ? ? ? ? ? ? ? @RequestParam("bookName") String bname){
? ? ? log.info(">>>> 使用@RequestParam注解傳遞參數(shù):{},{},{}", bid,bname,bookPrice);
? ? ? return "index";
? }
?
? @RequestMapping("/hello4/{bid}")
? public String toHello4(@PathVariable("bid") Integer bid){
? ? ? log.info(">>>> 使用@PathVariable注解傳遞參數(shù):{}", bid);
? ? ? return "index";
? }
?
// ? 能接受json數(shù)據(jù),前提導(dǎo)入了Jackson依賴,沒有導(dǎo)入Jackson依賴的話那進(jìn)不了這個(gè)方法
? @RequestMapping("/hello5")
? public String toHello5(@RequestBody Map map){
? ? ? System.out.println(map);
? ? ? return "index";
? }
?
// 不能接受json數(shù)據(jù)
? @RequestMapping("/hello6")
? public String toHello6(Map map){
? ? ? System.out.println(map);
? ? ? return "index";
? }
?
? @RequestMapping("/hello7")
? public String toHello7(Book book, @RequestBody Map map, @RequestHeader("jwt") String jwt){
? ? ? System.out.println(map);
? ? ? System.out.println(book);
? ? ? System.out.println(jwt);
? ? ? return "index";
? }
}
三、返回值
3.1.void
處理器對(duì)請(qǐng)求處理后,無需跳轉(zhuǎn)到其它任何資源,此時(shí)可以讓處理器方法返回 void。
處理器方法返回 void 的應(yīng)用場(chǎng)景,AJAX 響應(yīng)。
@RequestMapping("/queryStudents")
? ?public void queryStudents(HttpServletResponse response) throws IOException {
?
? ? ? ?//處理Ajax,使用json做數(shù)據(jù)格式
? ? ? ?Student student = new Student();
? ? ? ?student.setName("張三");
? ? ? ?student.setAge(18);
?
? ? ? ?try {
? ? ? ? ? ?ResponseUtil.writeJson(response,student);
? ? ? } catch (Exception e) {
? ? ? ? ? ?e.printStackTrace();
? ? ? }
? }
?
@Data
class Student{
? ?private String name;
? ?private Integer age;
}
3.2.String
@RequestMapping("/toHello")
public String toHello(){
? ?//邏輯視圖名
? ?return "hello";
}
返回類型為String,默認(rèn)被作為視圖名,指定邏輯視圖名,經(jīng)過視圖解析器解析為jsp物理路徑:/WEB-INF/page/success.jsp
3.3.String+Model
通過http://localhost:8080/springmvc01/toHello訪問請(qǐng)求方法,并經(jīng)過視圖解析器跳轉(zhuǎn)指定頁面,最后完成視圖模型數(shù)據(jù)渲染操作。
@RequestMapping("/toHello1")
? ?public String toHello1(Model model,HttpServletRequest request){
? ? ? ?//填充模型數(shù)據(jù)
? ? ? ?model.addAttribute("name","張三");
? ? ? ?request.setAttribute("role","管理員");
? ? ? ?//邏輯視圖名
? ? ? ?return "hello";
? }
3.4.ModelAndView
@RequestMapping("/toHello2")
? ?public ModelAndView toHello2(){
? ? ? ?ModelAndView mv = new ModelAndView();
? ? ? ?//填充模型數(shù)據(jù)
? ? ? ?mv.addObject("name","張三");
? ? ? ?mv.addObject("role","管理員");
? ? ? ?mv.setViewName("hello");
? ? ? ?//邏輯視圖名
? ? ? ?return mv;
? }
四、頁面跳轉(zhuǎn)
轉(zhuǎn)發(fā)(forward:path)和重定向(redirect:path)這兩種跳轉(zhuǎn)方式將會(huì)繞開視圖解析器的前綴和后綴;還有就是如果是在同一controller中則不用使用"/"從根目錄開始,而如果是在不同的controller則一定要從根目錄開始。
path為請(qǐng)求處理方法名,而非邏輯視圖名。
-
轉(zhuǎn)發(fā)(地址欄不變)
@RequestMapping("/helloPage1")
? ?public String toHelloPage1(){
? ? ? ?System.out.println("helloPage1");
? ? ? ?return "forward:toHello2";
? }
它相當(dāng)于“request.getRequestDispatcher("url").forward(request,response)”。使用轉(zhuǎn)發(fā),既可以轉(zhuǎn)發(fā)到j(luò)sp, 也可以轉(zhuǎn)發(fā)到其他的控制器方法。
-
重定向(地址欄改變)
@RequestMapping("/helloPage2")
? ?public String toHelloPage2(){
? ? ? ?System.out.println("helloPage2");
? ? ? ?return "redirect:toHello2";
? }
它相當(dāng)于“response.sendRedirect(url)”。需要注意的是,如果重定向到j(luò)sp頁面,則jsp頁面不能寫在WEB-INF目錄中,否則無法找到。文章來源:http://www.zghlxwxcb.cn/news/detail-699526.html
跳其它的controller文章來源地址http://www.zghlxwxcb.cn/news/detail-699526.html
@RequestMapping("/helloPage3")
? public String toHelloPage3(){
? ? ? System.out.println("helloPage3");
? ? ? return "forward:/demo/hello";
? }
?
? @RequestMapping("/helloPage4")
? public String toHelloPage4(){
? ? ? System.out.println("helloPage4");
? ? ? return "redirect:/demo/hello";
? }
到了這里,關(guān)于SpringMVC進(jìn)階:常用注解、參數(shù)傳遞和請(qǐng)求響應(yīng)以及頁面跳轉(zhuǎn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!