溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring mvc Controller和RestFul原理的示例分析

發(fā)布時(shí)間:2021-05-12 11:36:27 來源:億速云 閱讀:182 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Spring mvc Controller和RestFul原理的示例分析,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

控制器Controller

  • 控制器復(fù)雜提供訪問應(yīng)用程序的行為,通常通過接口定義或注解定義兩種方法實(shí)現(xiàn)。

  • 控制器負(fù)責(zé)解析用戶的請求并將其轉(zhuǎn)換為一個(gè)模型。

  • 在Spring MVC中一個(gè)控制器類可以包含多個(gè)方法

  • 在Spring MVC中,對于Controller的配置方式有很多種

實(shí)現(xiàn)Controller接口

Controller是一個(gè)接口,在org.springframework.web.servlet.mvc包下,接口中只有一個(gè)方法;

//實(shí)現(xiàn)該接口的類獲得控制器功能
public interface Controller {
  //處理請求且返回一個(gè)模型與視圖對象
  ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}

測試

編寫一個(gè)Controller類,ControllerTest1

// 定義控制器
// 注意點(diǎn):不要導(dǎo)錯(cuò)包,實(shí)現(xiàn)Controller接口,重寫方法;
public class ControllerTest1 implements Controller {

  public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    //返回一個(gè)模型視圖對象
    ModelAndView mv = new ModelAndView();
    mv.addObject("msg","Test1Controller");
    mv.setViewName("test");
    return mv;
  }
}

編寫完畢后,去Spring配置文件中注冊請求的bean;name對應(yīng)請求路徑,class對應(yīng)處理請求的類

<bean name="/t1" class="com.xiaohua.controller.ControllerTest1"/>

編寫前端test.jsp,注意在WEB-INF/jsp目錄下編寫,對應(yīng)我們的視圖解析器

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Kuangshen</title>
</head>
<body>
  ${msg}
</body>
</html>

配置Tomcat運(yùn)行測試,我這里沒有項(xiàng)目發(fā)布名配置的就是一個(gè) / ,所以請求不用加項(xiàng)目名,OK!

說明:

實(shí)現(xiàn)接口Controller定義控制器是較老的辦法

缺點(diǎn)是:一個(gè)控制器中只有一個(gè)方法,如果要多個(gè)方法則需要定義多個(gè)Controller;定義的方式比較麻煩;

使用注解@Controller

@Controller注解類型用于聲明Spring類的實(shí)例是一個(gè)控制器(在講IOC時(shí)還提到了另外3個(gè)注解);

Spring可以使用掃描機(jī)制來找到應(yīng)用程序中所有基于注解的控制器類,為了保證Spring能找到你的控制器,需要在配置文件中聲明組件掃描。

<!-- 自動(dòng)掃描指定的包,下面所有注解類交給IOC容器管理 -->
<context:component-scan base-package="com.xiaohua.controller"/>

增加一個(gè)ControllerTest2類,使用注解實(shí)現(xiàn);

// @Controller注解的類會(huì)自動(dòng)添加到Spring上下文中
@Controller
public class ControllerTest2{

  //映射訪問路徑
  @RequestMapping("/t2")
  public String index(Model model){
    //Spring MVC會(huì)自動(dòng)實(shí)例化一個(gè)Model對象用于向視圖中傳值
    model.addAttribute("msg", "ControllerTest2");
    //返回視圖位置
    return "test";
  }

}

運(yùn)行tomcat測試

可以發(fā)現(xiàn),我們的兩個(gè)請求都可以指向一個(gè)視圖,但是頁面結(jié)果的結(jié)果是不一樣的,從這里可以看出視圖是被復(fù)用的,而控制器與視圖之間是弱偶合關(guān)系。

RequestMapping
@RequestMapping注解用于映射url到控制器類或一個(gè)特定的處理程序方法??捎糜陬惢蚍椒ㄉ?。用于類上,表示類中的所有響應(yīng)請求的方法都是以該地址作為父路徑。

為了測試結(jié)論更加準(zhǔn)確,我們可以加上一個(gè)項(xiàng)目名測試 myweb

只注解在方法上面

@Controller
public class TestController {
  @RequestMapping("/h2")
  public String test(){
    return "test";
  }
}

訪問路徑:http://localhost:8080 / 項(xiàng)目名 / h2

同時(shí)注解類與方法

@Controller
@RequestMapping("/admin")
public class TestController {
  @RequestMapping("/h2")
  public String test(){
    return "test";
  }
}

訪問路徑:http://localhost:8080 / 項(xiàng)目名/ admin /h2 , 需要先指定類的路徑再指定方法的路徑;

RestFul風(fēng)格
Restful就是一個(gè)資源定位及資源操作的風(fēng)格。不是標(biāo)準(zhǔn)也不是協(xié)議,只是一種風(fēng)格。基于這個(gè)風(fēng)格設(shè)計(jì)的軟件可以更簡潔,更有層次,更易于實(shí)現(xiàn)緩存等機(jī)制。

功能

  • 資源:互聯(lián)網(wǎng)所有的事物都可以被抽象為資源

  • 資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進(jìn)行操作。

  • 分別對應(yīng) 添加、 刪除、修改、查詢。

傳統(tǒng)方式操作資源 :通過不同的參數(shù)來實(shí)現(xiàn)不同的效果!方法單一,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操作資源 : 可以通過不同的請求方式來實(shí)現(xiàn)不同的效果!如下:請求地址一樣,但是功能可以不同!

  • 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

學(xué)習(xí)測試

在新建一個(gè)類 RestFulController

@Controller
public class RestFulController {
}

在Spring MVC中可以使用 @PathVariable 注解,讓方法參數(shù)的值對應(yīng)綁定到一個(gè)URI模板變量上。

@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會(huì)自動(dòng)實(shí)例化一個(gè)Model對象用于向視圖中傳值
    model.addAttribute("msg", "結(jié)果:"+result);
    //返回視圖位置
    return "test";

  }

}

我們來測試請求查看下

使用路徑變量的好處?

  • 使路徑變得更加簡潔;

  • 獲得參數(shù)更加方便,框架會(huì)自動(dòng)進(jìn)行類型轉(zhuǎn)換。

  • 通過路徑變量的類型可以約束訪問參數(shù),如果類型不一樣,則訪問不到對應(yīng)的請求方法,如這里訪問是的路徑是/commit/1/a,則路徑與方法不匹配,而不會(huì)是參數(shù)轉(zhuǎn)換失敗。

我們來修改下對應(yīng)的參數(shù)類型,再次測試

//映射訪問路徑
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model model){

  String result = p1+p2;
  //Spring MVC會(huì)自動(dòng)實(shí)例化一個(gè)Model對象用于向視圖中傳值
  model.addAttribute("msg", "結(jié)果:"+result);
  //返回視圖位置
  return "test";

}

使用method屬性指定請求類型

用于約束請求的類型,可以收窄請求范圍。指定請求謂詞的類型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等

我們來測試一下:

增加一個(gè)方法

//映射訪問路徑,必須是POST請求
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String index2(Model model){
  model.addAttribute("msg", "hello!");
  return "test";
}

我們使用瀏覽器地址欄進(jìn)行訪問默認(rèn)是Get請求,會(huì)報(bào)錯(cuò)405:

如果將POST修改為GET則正常了;

//映射訪問路徑,必須是Get請求
@RequestMapping(value = "/hello",method = {RequestMethod.GET})
public String index2(Model model){
  model.addAttribute("msg", "hello!");
  return "test";
}

小結(jié):

Spring MVC 的 @RequestMapping 注解能夠處理 HTTP 請求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。

所有的地址欄請求默認(rèn)都會(huì)是 HTTP GET 類型的。

方法級(jí)別的注解變體有如下幾個(gè): 組合注解

  • @GetMapping

  • @PostMapping

  • @PutMapping

  • @DeleteMapping

  • @PatchMapping

  • @GetMapping 是一個(gè)組合注解

它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一個(gè)快捷方式。

關(guān)于“Spring mvc Controller和RestFul原理的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI