SpringMVC註解作用及用法

SpringMVC官網 註解總結

@PathVariable

@PathVariable有什麼作用?用法是怎樣的?
@PathVariable註解使用
@PathVariable詳解

  • 作用:將URL中的佔位符參數綁定到Controller方法的入參中。
  • 用法:URL 中的 {xxx} 佔位符可以通過@PathVariable(“xxx“) 綁定到操作方法的入參中。
@RequestMapping(value = "/push/{id}", method = RequestMethod.GET)
public ResponseResult list(HttpServletRequest request, 
                           @PathVariable("id") String id)
  • 注意:如果方法入參名和佔位符名稱一致,可以省略後面的(“xxx”);如果不一樣則要寫出。

@Controller

springMVC的常用註解有哪些?

  • 作用:用於標記在一個類上,使用它標記的類就是SpringMVC Controller對象,用於定義一個控制器類。
  • 用法:將Controller類交給Spring進行管理,方式有以下兩種:
<!--方式一-->
<bean class="com.cqvie.handler.HelloWorld"/>
<!--方式二-->
< context:component-scan base-package = "com.cqvie" /> <!-- 路徑寫到controller的上一層 -->
package com.cqvie.handler;

import org.springframework.stereotype.Controller;

@Controller
public class HelloWorld {

    @RequestMapping("/helloworld")
    public String sayHello() {
        System.out.println("Hello World!");
        return "success";
    }
}
  • 注意:只是將Controller對象定義還不能使用,必須要對它進行管理,纔可以讓spring認識它

@RequestMapping

參考同上。

  • 作用:用來處理請求地址映射的註解,可以標記在上或者方法上。用於上,表明該類的所有響應請求的方法都是以該地址映射爲父地址。
  • 用法:@RequestMapping有六個屬性
屬性 作用
value 指定請求的實際地址
method 指定請求的method類型,GET、PUT、POST、DELETE
consumes 指定處理請求的提交內容類型,application/json, text/html
produces 指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回
params 指定request中必須包含某些參數值時才讓該方法處理
headers 指定request中必須包含某些指定的header值,才能讓該方法處理請求
屬性value

根據url可以分爲4種情況:

  1. 普通的url具體值,如"/book";
  2. url可以包含變量,如"/book/{id}";
  3. ant風格,如"?"," * “,” ** ";
  4. 正則表達式;
  5. 或關係,如
@RequestMapping(value={"/get","/fetch"})
屬性params

指定request中必須包含某些參數值時,才讓該方法處理
@RequestMapping(params=“action=del”),請求參數包含**“action=del”**,如:http://localhost:8080/book?action=del

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    
  }
}

🏠:僅處理請求中包含了名爲"myParam",值爲"myValue"的請求。

屬性headers

指定request中必須包含某些指定的header值,才能讓該方法處理請求
@RequestMapping(value="/header/id", headers = “Accept=application/json”):表示請求的URL必須爲"/header/id 且請求頭中必須有**“Accept =application/json”**參數即可匹配。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    
  }
}

🏠:僅處理request的header中包含了指定"Refer"請求頭和對應值爲"http://www.ifeng.com/"的請求。

屬性consumes

指定處理請求的提交內容類型(Content-Type),例如application/json, text/html。

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    
   
}

🏠:方法僅處理request Content-Type爲"application/json"類型的請求。

屬性produces

指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回。

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    
    
}

🏠:方法僅處理request請求中Accept頭中包含了"application/json"的請求,同時暗示了返回的內容類型爲application/json。

@Resource和@Autowired

兩者都是做bean引入時的註解。但是@Resource並不是爲Spring提供的註解,它的包是javax.annotation.Resource,需要引入,不過spring支持這種引用。

something @Resource @Autowired
共同點 都可以寫在字段setter方法 如果都寫在字段上,則不需要再寫setter方法
不同點① 默認按照ByName的方式自動注入,由J2EE提供,需要導入包 只按照ByType的方式注入,爲Spring提供的註解,需要導入包:org.springframework.beans.factory.annotation.Autowired
不同點② name和type兩個屬性 不可以變換
  • 注意
    1. @Autowired註解是按照類型(byType)裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它的required屬性爲false。如果我們想使用按照名稱(byName)來裝配,可以結合@Qualifier註解一起使用。
    public class HelloWorld{ 
           @Autowired 
           @Qualifier("userDao") 
    private UserDao userDao; 
    }
    
    1. @Resource有兩個重要的屬性:nametype,而Spring將@Resource註解的name屬性解析爲bean的名字,而type屬性則解析爲bean的類型。所以,如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不制定name也不制定type屬性,這時將通過反射機制使用byName自動注入策略。
    public class HelloWorld{
    // 下面兩種@Resource只要使用一種即可
    @Resource(name="userDao")
    private UserDao userDao; // 用於字段上
    
    @Resource(name="userDao")
    public void setUserDao(UserDao userDao) { // 用於屬性的setter方法上
        this.userDao = userDao;
       }
    }
    

注:最好是將@Resource放在setter方法上,因爲這樣更符合面向對象的思想,通過set、get去操作屬性,而不是直接去操作屬性。

@RequestParam

@RequestBody和@RequestParam區別
@RequestParam詳解

  • 作用:將請求參數區數據映射到Controller方法的參數上
  • 用法:@RequestParam註解有三個參數
    1. value:請求中傳入參數的名稱,如果不設置後臺接口的value值,則會默認爲該變量名。
    2. required:該參數是否爲必傳項。默認是true,表示請求中一定要傳入對應的參數,否則會報404錯誤,如果設置爲false時,當請求中沒有此參數,將會默認爲null;而對於基本數據類型的變量,則必須有值,如果沒有會拋出空指針異常。如果允許空值,則接口中變量需要使用包裝類來聲明。
    3. defaultValue:參數的默認值,如果請求中沒有同名的參數時,該變量默認爲此值。注意默認值可以使用SpEL表達式,如"#{systemProperties[‘java.vm.version’]}"
  • 注意:如果在請求中傳入多個同名參數,比如:
    url?userName=zhl&userName=holley時:
    其實此時傳入的數據格式是:“zhl,holley”,即多個數據之間使用逗號分隔開,在後臺接口中可以使用數組或者list類型的變量來接收。
public String requestparam8(@RequestParam(value="userName") String []  userNames) 
//或者
public String requestparam8(@RequestParam(value="list") List<String> list) 

@RequestBody

@RequestBody和@RequestParam區別

  • 作用:可以批量修改、增加、刪除數據,處理application/json類型的數據時可用。
  • 用法:POST\DELET\PUT,GET不可用

@ResponseBody

  • 作用:該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換爲指定格式後,寫入到Response對象的body數據區。把返回對象自動序列化成HttpResponse的。
    -用法:返回的數據不是html標籤的頁面,而是其他某種格式的數據時(如json、xml等)使用。

@RestController

@RestController註解初步理解

作用等同於@Controller + @ResponseBody

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