Spring MVC學習(三)----註解使用

@Controller

註解位置: 標記在POJO上(類上)
作用: 通過<context:component-scan/>掃描相應的類包,即可使POJO稱爲一個能處理HTTP請求的控制器
解釋: 在POJO類定義處標記@Controller,再通過<context:component-scan/>掃描相應的類包,即可使POJO稱爲一個能處理HTTP請求的控制器。

@Controller
public class UserController {
}

@ResponseBody

註解位置: 標註在類上或者方法上
作用: 將返回值的轉化爲JSON格式,如果該該註解放在類上,它是繼承的,每個方法都就有了該註解。不需要再添加到方法上了。
解釋: 在類上或者方法上標註@ResponseBody,它將返回值都轉化爲JSON格式

@Controller
@ResponseBody
public class TestController {
}

@Controller
public class TestController {
  @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
  @ResponseBody
  public Object getUser() {
      return null;
  }
}

@RestController

註解位置: 標記在POJO上(類上)
作用: @Controller+@ResponseBody 的結合體
解釋: @Controller+@ResponseBody 的結合體

@RestController
public class TestController {
    // 同上效果
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public Object getUser() {
        return null;
    }
}

@RequestMapping

註解位置: 控制器的類上或者方法上
作用: 用於映射請求的路徑與對應的方法。
解釋: 在控制器的類上以及方法上定義出都可以標註@RequestMapping,類定義處的@RequsetMapping提供初步的請求映射信息,方法定義出的@RequsetMapping提供進一步的戲份映射信息,DispatcherServlet截取請求後,就是通過控制器上的@RequestMapping提供的映射信息對清求所對應的處理方法。
參數:

public @interface RequestMapping {

    @AliasFor("path")
    String[] value() default {};
	//請求的URL
    @AliasFor("value")
    String[] path() default {};
	//請求的方法
    RequestMethod[] method() default {};
    //請求參數
    String[] params() default {};
	//報文頭
    String[] headers() default {};

}

params、headers支持簡單的映射表達式,
params表達式爲例 : headers參照params

    params="param1" :表示請求需要包含param1的請求參數
    params="!param1" :請求不能包含param1的請求參數
    params="param1!=val": 表示請求包含param1的請求參數,但是值不能爲val
    params={"param1=val","param2"}:表示必須包含param1和param2的兩個請求參數。切param1值爲val,

例:

@RestController
public class TestController {
    @RequestMapping(value = "/updateUser",params = {"a=1","b"},method = RequestMethod.GET)
    public Object getUser(@RequestParam("a") String a ,@RequestParam("b") String b) {
        return a+"------"+b;
    }
    // 請求 /updateUser?a=2&b  報錯 400 Parameter conditions "a=1, b" not met for actual request parameters:  表示不滿足a=1,b 參數,說明必須要有a、b兩個參數,切a=1
    // 請求 /updateUser?a=1&b=2 OK  1------2
}

以下註解都是根據對請求做處理的註解,他們都在形式參數位置

@RequestBody——獲取請求參數中的json字符串

很常用,推薦鏈接

@RequestParam——獲取傳入參數的值

作用: 指定參數名獲取傳入參數的值,如果方法參數是Map<String、String>、MultiValueMap<String、String>或HttpHeaders,則映射將填充所有頭部名稱和值。
參數:

	//同name()方法
  	 @AliasFor("name")
    String value() default "";
    //綁定到的請求參數的名稱。
    @AliasFor("value") 
    String name() default "";
	//參數是否必須  默認是true,如果請求不存在該參數,則拋出異常;如果爲false,如果請求不存在該參數,形參爲null ,
    boolean required() default true;

    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";

例子

@RequestMapping(value = "/test")
public Object test(@RequestParam(value = "name",required = false) String name
,@RequestParam(value = "id") String id) {
        return id+"-----"+name;
    }
//get   /test?name=sjy&id=1    輸出  1-----sjy
//get   /test?id=1			 輸出  1-----null
//get   /test?name=sjy         輸出 400 – 錯誤的請求

@PathVariable—— 獲取定義在路徑中的參數值

**作用:**用來映射URL中的佔位符到目標方法的參數中
參數:

 //要綁定到的路徑變量的名稱。
 String value() default ""; 

例:

@RequestMapping(value = "/test1/{id}/test1/{name}")
public Object test1(@PathVariable(value = "id") String id,
    @PathVariable(value = "name") String name) {
        return id+"-----"+name;
    }
//請求   /test1/11/test1/211    輸出   11-----211

@MatrixVariable——使用矩陣變量綁定參數

作用: 使用矩陣變量綁定參數,Spring4.0已經全面支持Matrix Variable,該註解似的開發人員能夠將請求中的矩陣變量綁定到處理器的方法參數中。
Matrix Variable中,多個變量可以使用”;“(分號)分隔,
提示: 默認Spring MVC中Matrix Variable功能是關閉的,如果要開啓該功能,需要在spring-mvc配置文件中添加如下設置 <mvc:annotation-driven enable-matrix-variables=“true”/> 。

<?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:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           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">
           <!--開啓Matrix Variable功能-->
    <mvc:annotation-driven enable-matrix-variables="true"/>
    <context:component-scan base-package="com.sjy"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp"/>
</beans>

如果在spring boot 想要使用該功能需要如下配置,重寫WebMvcConfigurer接口的configurePathMatch方法即可

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper=new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

例如: /test2;id=1;name=sjy
參數:

	// 同name()方法
	@AliasFor("name") 
    String value() default "";
	// 矩陣變量的名稱。如果方法參數是Map<String、String>、MultiValueMap<String、String>或HttpHeaders,則映射將填充所有頭部名稱和值。
    @AliasFor("value")
    String name() default "";
	//如果需要消除歧義,矩陣變量所在的URI路徑變量的名稱 看下面例子理解
    String pathVar() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
	//是否需要矩陣變量。 
    boolean required() default true;

例子:

@RequestMapping(value="test2/{id}/p/{name}")
public Object test2(@MatrixVariable(pathVar = "id") Map<String, String[]> id,
@MatrixVariable(pathVar = "name") Map<String, String[]> name){
    return id+"-----"+name;
    }
    
//請求  /test2/1s;a=1,2,3;b=a;c=cc/p/sjy;s=2;j=3;y=3;d=a,b,c,d   
//輸出響應  {a=[1, 2, 3], b=[a], c=[cc]}-----{s=[2], j=[3], y=[3], d=[a, b, c, d]}
//如果將@MatrixVariable註解中的pathVar屬性去掉
//相同的請求
//輸出響應  {a=[1, 2, 3], b=[a], c=[cc], s=[2], j=[3], y=[3], d=[a, b, c, d]}-----{a=[1, 2, 3], b=[a], c=[cc], s=[2], j=[3], y=[3], d=[a, b, c, d]}

//完整性測試
@RequestMapping(value = "/test3/{ownerId}/test3/{petId}", method = RequestMethod.GET)
    public Object findPet(
    @PathVariable(value = "ownerId") Integer ownerId ,
    @PathVariable(value = "petId") Integer petId ,
    @MatrixVariable(value = "q", pathVar = "ownerId") String q,
    @MatrixVariable(pathVar = "ownerId") Map<String, String> matrixVars,
    @MatrixVariable(pathVar = "petId") Map<String, String> petMatrixVars) {
      return "ownerId: " + ownerId + "----petId:" + petId + "----q: " + q + 
                "----matrixVars: " + matrixVars + "---petMatrixVars: " + petMatrixVars;
    }
	// 請求   /test3/1;q=1,2,3;b=a;c=cc/test3/12;s=2;j=3;y=3;d=a,b,c,d
    // 輸出響應 ownerId: 1----petId: 12----q: 1,2,3----matrixVars: {q=[1, 2, 3], b=[a], c=[cc]}---petMatrixVars: {s=[2], j=[3], y=[3], d=[a, b, c, d]}

@RequestHeader——請求報文頭的值

**作用:**指定報文頭參數名獲取傳入參數的值,如果方法參數是Map<String、String>、MultiValueMap<String、String>或HttpHeaders,則映射將填充所有頭部名稱和值。
參數:

 	 @AliasFor("name")
    String value() default "";
	//要綁定到的請求頭的名稱
    @AliasFor("value")
    String name() default "";
	//是否需要該參數
    boolean required() default true;

例: 使用PostMan

@RequestMapping("/test4")
    public Object test4(@RequestHeader Map<String, String> map){
        return map.toString();
    }

在這裏插入圖片描述

@CookieValue——請求中Cookie的值

與@RequestHeader同理,不過是獲取的Cookie中的值。


當然在形參那裏可以使用ServletAPI最想作爲入參,如HttpServletRequest、HttpServletResponse等,也可以使用I/O作爲入參如,OutPutStream等


如有不當之處,歡迎指正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章