SpringMVC重點知識總結

SpringMVC總結

1. SpringMVC簡介

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

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). 視圖負責將結果顯示到客戶端java

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來配置DispatcherServletweb

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方式spring

<?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註解用來聲明控制器json

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

接受請求的輸入
@RequestParam註解 做爲查詢參數
@PathVariable註解 路徑變量spring-mvc

5. Spring RESTful

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

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

在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對請求返回的內容進行驗證;
相關文章
相關標籤/搜索