SpringMVC重點知識總結

  • 2019 年 11 月 1 日
  • 筆記

SpringMVC總結

1. SpringMVC簡介

MVC即模型-視圖-控制器(Model-View-Controller)

Spring Web MVC是一種基於Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架,即使用了MVC架構模式的思想,將web層進行職責解耦,基於請求驅動指的就是使用請求-響應模型,框架的目的就是幫助我們簡化開發,Spring Web MVC也是要簡化我們日常Web開發的。

2. SpringMVC運行原理

1). 客戶端請求提交到DispatcherServlet
2). 由DispatcherServlet控制器查詢一個或多個HandlerMapping,找到處理請求的Controller
3). DispatcherServlet將請求提交到Controller
4). Controller調用業務邏輯處理後,返回ModelAndView
5). DispatcherServlet查詢一個或多個ViewResoler視圖解析器,找到ModelAndView指定的視圖
6). 視圖負責將結果顯示到客戶端

3. 常用註解

  • @Controller負責註冊一個bean到spring上下文中
  • @RequestMapping 註解為控制器指定可以處理哪些 URL 請求
  • @RequestBody 該註解用於讀取Request請求的body部分數據,使用系統默認配置的HttpMessageConverter進行解析,然後把相應的數據綁定到要返回的對象上 ,再把HttpMessageConverter返回的對象數據綁定到 controller中方法的參數上
  • @ResponseBody 該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response對象的body數據區
  • @ModelAttribute 在方法定義上使用 @ModelAttribute 註解:Spring MVC 在調用目標處理方法前,會先逐個調用在方法級上標註了@ModelAttribute 的方法,在方法的入參前使用 @ModelAttribute 註解:可以從隱含對象中獲取隱含的模型數據中獲取對象,再將請求參數 –綁定到對象中,再傳入入參將方法入參對象添加到模型中
  • @RequestParam 在處理方法入參處使用 @RequestParam 可以把請求參 數傳遞給請求方法
  • @PathVariable 綁定 URL 佔位符到入參
  • @ExceptionHandler 註解到方法上,出現異常時會執行該方法
  • @ControllerAdvice 使一個Contoller成為全局的異常處理類,類中用@ExceptionHandler方法註解的方法可以處理所有Controller發生的異常

4. SpringMVC配置與使用

4.1 配置DispatcherServlet

Java配置方式

通過AbstractAnnotationConfigDispatcherServlet-Initializer來配置DispatcherServlet

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;    public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {        @Override      protected Class<?>[] getRootConfigClasses() {          return new Class<?>[] { RootConfig.class };      }        @Override      protected Class<?>[] getServletConfigClasses() {          return new Class<?>[] { WebConfig.class };      }        @Override      protected String[] getServletMappings() {          return new String[] { "/" };      }    }

xml配置方式

傳統web.xml方式

<?xml version="1.0" encoding="UTF-8"?>  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"           version="2.5">    <display-name>Springmvc</display-name>    <welcome-file-list>        <welcome-file>index.html</welcome-file>    </welcome-file-list>      <!--Spring監聽器-->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>        <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>        <!--前端控制器-->    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!--默認找/resource/[servlet名稱]-servlet.xml-->        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:springmvc.xml</param-value>        </init-param>    </servlet>      <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <!--1./* 攔截所有請求   2. *.action *.do 攔截以.action .do 結尾的請求  3. / 攔截除.jsp以外請求-->        <url-pattern>/</url-pattern>    </servlet-mapping>    </web-app>

4.2 啟用Spring MVC

Java配置方式

@Configuration  @EnableWebMvc  @ComponentScan("com.fiberhome.tongl.spittr.web")  public class WebConfig extends WebMvcConfigurerAdapter {        @Bean      public ViewResolver viewResolver() {          InternalResourceViewResolver resolver = new InternalResourceViewResolver();          resolver.setPrefix("/WEB-INF/views/");          resolver.setSuffix(".jsp");          resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);          return resolver;      }        @Override      public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {          configurer.enable();      }  }

xml配置方式

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns:context="http://www.springframework.org/schema/context"         xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/cache"         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">          <!--掃描各層@Component-->      <context:component-scan base-package="com.fiberhome"/>        <!--註解驅動-->      <mvc:annotation-driven />      <!--視圖解析器-->      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">          <property name="prefix" value="/WEB-INF/jsp/"/>          <property name="suffix" value=".jsp"/>      </bean>    </beans>

4.3 編寫控制器

@Controller註解用來聲明控制器

@RequestMapping註解 value屬性指定了這個方法所要處理的請求路徑,method屬性細化了它所處理的HTTP方法

接受請求的輸入
@RequestParam註解 作為查詢參數
@PathVariable註解 路徑變數

5. Spring RESTful

近幾年來,以資訊為中心的表述性狀態轉移(Representational State Transfer,REST)已成為替換傳統SOAP Web服務的流行方案。SOAP一般會關注行為和處理,而REST關注的是要處理的數據。

REST與RPC(remote procedure call,遠程過程調用)幾乎沒有任何關係。RPC是面向服務的,並關注於行為和動作;而REST是面向資源的,強調描述應用程式的事物和名詞。

在REST中,資源通過URL進行識別和定位。至於RESTful URL的結構並沒有嚴格的規則,但是URL應該能夠識別資源,而不是簡單的發一條命令到伺服器上。再次強調,關注的核心是事物,而不是行為。

消息轉換

消息轉換(message conversion)能夠將控制器產生的數據轉換為服務於客戶端的表述形式。如json、xml等。

@RequestMapping produces=「application/json」 表明這個方法只處理預期輸出為JSON的請求 可結合@ResponseBody使用
consumes屬性 結合@RequestBody

@ResponseBody註解會告知Spring,我們要將返回的對象作為資源發送給客戶端,並將其轉換為客戶端可接受的表述形式。更具體地講,DispatcherServlet將會考慮到請求中Accept頭部資訊,並查找能夠為客戶端提供所需表述形式的消息轉換器。

@RequestBody也能告訴Spring查找一個消息轉換器,將來自客戶端的資源表述轉換為對象。

@RestController來代替@Controller的話,Spring將會為該控制器的所有處理方法應用消
息轉換功能。就不必為每個方法都添加@ResponseBody了。

發送錯誤資訊

  1. @ExceptionHandler註解能夠用到控制器方法中,用來處理特定的異常。

  2. 用@ResponseStatus註解可以指定狀態碼

  3. 控制器方法可以返回ResponseEntity對象,該對象能夠包含更多響應相關的元數據;

6. MockMvc測試

對模組進行集成測試時,希望能夠通過輸入URL對Controller進行測試,如果通過啟動伺服器,建立http client進行測試,這樣會使得測試變得很麻煩,比如,啟動速度慢,測試驗證不方便,依賴網路環境等,所以為了可以對Controller進行測試,引入了MockMVC。

MockMvc實現了對Http請求的模擬,能夠直接使用網路的形式,轉換到Controller的調用,這樣可以使得測試速度快、不依賴網路環境,而且提供了一套驗證的工具,這樣可以使得請求的驗證統一而且很方便。

測試邏輯

  1. MockMvcBuilder構造MockMvc的構造器;
  2. mockMvc調用perform,執行一個RequestBuilder請求,調用controller的業務處理邏輯;
  3. perform返回ResultActions,返回操作結果,通過ResultActions,提供了統一的驗證方式;
  4. 使用StatusResultMatchers對請求結果進行驗證;
  5. 使用ContentResultMatchers對請求返回的內容進行驗證;