四是偷、Controller及RestFul
目錄:控制器Controller蛋铆、實現Controller接口放接、注解@Controller纠脾、RequestMapping、RestFul風格
1.通過配置實現
- 控制器復雜提供訪問應用程序的行為糊渊,通常通過接口定義或注解定義兩種方法實現汉操。
- 控制器負責解析用戶的請求并將其轉換為一個模型磷瘤。
- 在Spring MVC中一個控制器類可以包含多個方法。
- 在Spring MVC中针炉,對于Controller的配置方式有很多種篡帕。
2.實現Controller接口
Controller是一個接口镰烧,在org.springframework.web.servlet.mvc包下怔鳖,接口中只有一個方法结执。
//實現該接口的類獲得控制器功能
public interface Controller {
//處理請求且返回一個模型與視圖對象
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
測試:
①新建一個Moudle,將上述代碼進行如下修改懂傀。
Ⅰ刪掉HelloController蹬蚁。
Ⅱmvc的配置文件只留下視圖解析器缚忧。
②編寫一個Controller類ControllerTest1。
//定義控制器
//注意:不要導錯jar包蒙具,實現Controller接口后重寫方法
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test");
return mv;
}
}
3)編寫完畢后,去Spring配置文件中注冊請求的bean衡招。(name對應請求路徑始腾,class對應處理請求的類)
<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
4)編寫前端test.jsp,注意在WEB-INF/jsp目錄下編寫穗椅,對應視圖解析器。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC</title>
</head>
<body>
${msg}
</body>
</html>
5)配置Tomcat運行測試宣鄙。(http://localhost:8080/t1)
說明:實現接口Controller定義控制器的辦法比較老冻晤。
缺點:一個控制器中只有一個方法明也,如果要多個方法則需要定義多個Controller,定義的方式比較麻煩蜻势。
3.注解@Controller
@Controller注解類型用于聲明Spring類的實例是一個控制器握玛。
Spring可以使用掃描機制來找到應用程序中所有基于注解的控制器類甫菠,為了保證Spring能找到相應的控制器挠铲,需要在配置文件中聲明組件掃描。
<!-- 自動掃描指定的包寂诱,下面所有注解類交給IOC容器管理 -->
<context:component-scan base-package="com.ping.controller"/>
增加一個ControllerTest2類拂苹,通過注解來實現。
//@Controller注解的類會自動添加到Spring上下文中
@Controller
public class ControllerTest2{
//映射訪問路徑
@RequestMapping("/t2")
public String index(Model model){
//Spring MVC會自動實例化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "ControllerTest2");
//返回視圖位置
return "test";
}
}
運行Tomcat痰洒,進行測試瓢棒。
結論:可以發(fā)現兩個請求都可以指向一個視圖,但是頁面結果的結果是不一樣的丘喻,從這里可以看出視圖是被復用的脯宿,而控制器與視圖之間是弱偶合關系。
4.RequestMapping
@RequestMapping
@RequestMapping注解用于映射url到控制器類或一個特定的處理程序方法泉粉×梗可用于類或方法上叽躯。用于類上,表示類中的所有響應請求的方法都是以該地址作為父路徑憨募。
只注解在方法上面:
@Controller public class TestController {
@RequestMapping("/t1")
public String test(){
return "test";
}
}
訪問路徑:http://localhost:8080/項目名/t1
注解類與方法:
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/t1")
public String test(){
return "test";
}
}
訪問路徑:http://localhost:8080/項目名/admin/t1 , 需要先指定類的路徑再指定方法的路徑媳危。
5.RestFul 風格
概念:Restful就是一個資源定位及資源操作的風格暮蹂。不是標準也不是協議,只是一種風格∏诚ぃ基于這個風格設
計的軟件可以更簡潔,更有層次,更易于實現緩存等機制。
資源:互聯網所有的事物都可以被抽象為資源。
功能:資源操作:使用POST、DELETE、PUT弟塞、GET,使用不同方法對資源進行操作,分別對應添加、 刪除、修改、查詢。
傳統方式操作資源:通過不同的參數來實現不同的效果隔崎,方法單一钓株。(post 和 get)
http://127.0.0.1/item/queryItem.action?id=1 查詢摆霉,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新向挖,POST
http://127.0.0.1/item/deleteItem.action?id=1 刪除徊件,GET或POST
使用RestFul操作資源:可以通過不同的請求方式來實現不同的效果部翘。(請求地址一樣,但是功能可以不同)
http://127.0.0.1/item/1 查詢蛔翅,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新爵政,PUT
http://127.0.0.1/item/1 刪除徽千,DELETE
測試:
①新建一個類RestFulController。
@Controller public class RestFulController {
}
②在Spring MVC中可以使用@PathVariable注解荠诬,讓方法參數的值對應綁定到一個URL模板變量上钧嘶。
@Controller
public class RestFulController {
//映射訪問路徑
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC會自動實例化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "結果:"+result);
//返回視圖位置
return "test";
}
}
使用路徑變量的好處:
Ⅰ使路徑變得更加簡潔。
Ⅱ獲得參數更加方便苟呐,框架會自動進行類型轉換。
Ⅲ通過路徑變量的類型可以約束訪問參數局冰,如果類型不一樣测蘑,則訪問不到對應的請求方法,如這里訪問是的路徑是/commit/1/a康二,則路徑與方法不匹配碳胳,而不會是參數轉換失敗。
③修改對應的參數類型沫勿,并進行再次測試挨约。
//映射訪問路徑
@RequestMapping("/commit/{p1}/{p2}")
public String index(
@PathVariable int p1, @PathVariable String p2, Model model){
String result = p1+p2;
//Spring MVC會自動實例化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "結果:"+result);
//返回視圖位置
return "test";
}
使用method屬性指定請求類型
用于約束請求的類型,可以收窄請求范圍产雹。指定請求謂詞的類型如GET诫惭、POST、HEAD蔓挖、OPTIONS夕土、PUT、PATCH瘟判、DELETE怨绣、TRACE等。
測試:
Ⅰ增加一個方法拷获。
//映射訪問路徑蜓萄,必須是POST請求
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String index2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
Ⅱ使用瀏覽器地址欄進行訪問默認是Get請求惶凝,會報錯405研乒。
Ⅲ如果將POST修改為GET則沒有錯誤摔桦。
//映射訪問路徑轴猎,必須是Get請求
@RequestMapping(value = "/hello",method = {RequestMethod.GET})
public String index2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
小結:Spring MVC的@RequestMapping注解能夠處理HTTP請求的方法啥刻,比如GET刺下、PUT共郭、POST树埠、DELETE以及PATCH糠馆。所有的地址欄請求默認都會是HTTP GET類型的。
方法級別的注解變體有如下幾個:組合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping是一個組合注解它所扮演的是@RequestMapping(method =RequestMethod.GET)的一個快捷方式怎憋,一般使用這種方式會比較多又碌。