springmvc常用註解學習

一、註解類配置

要使用springmvc的註解類,需要在springmvc.xml配置文件中用context:component-scan/掃描:

二、五大重要的註解類

1.RequestMapping註解

RequestMapping註解類的使用方法

在Controller控制器類的類定義和方法定義處都可以標註@RequestMapping註解
DispatcherServlet截獲請求後,就可以通過控制器上的@RequestMapping提供的映射信息確定請求所對應的處理方法

複製代碼
package net.quickcodes.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home") //類級別,可以不需要,如果要了,下面所有的請求路徑前都需要加上“/home”
public class IndexController {

    //方法級別,必須有,決定這個方法處理哪個請求(這裏處理/helloworld/home/index.html請求)
    @RequestMapping(value = "/index")
    public String helloWorld(){
        return "index";//"WEB-INF/page/index.jsp"
    }
    
}
複製代碼

 

RequestMapping註解類的屬性

RequestMapping註解類的屬性,分別有 value, method, consumes, produces, params, headers
1>.value屬性
• 代表具體的請求路徑,比如上面的 "/home", "/index"都是value的值
• value可以省略,就像例子中一樣,直接用 @RequestMapping("/home") 的格式,它等同於@RequestMapping(value = "/home")

2>.method屬性
• 指定請求的method類型, GET、POST、PUT、DELETE等:
例:@RequestMapping(value = "/login", method = RequestMethod.POST) 那麼只有發送POST請求才會觸發這個方法
• 它的值既可以是字符串也可以是數組:
例:@RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})

3>.consumes屬性
• 指定請求的提交內容類型(Content-Type),例如application/json, text/html
例:@RequestMapping(value = "/login", consumes = "application/json"
• 它的值既可以是字符串也可以是數組
例:@RequestMapping(value = "/login", consumes = {"application/json", "text/html"})

4>.produces屬性
• 指定返回的內容的類型(Content-Type),例如application/json, text/html
例:@RequestMapping(value = "/login", produces = "application/json"
• 它的值既可以是字符串也可以是數組
例:@RequestMapping(value = "/login", produces = {"application/json", "text/html"})

5>.params屬性
• 指定請求中必須包含某些參數值,纔會觸發這個處理方法
例:@RequestMapping(value = "/login", params = "id=1"
• 參數中除了使用=等號外,還可以使用!=號,表示在參數的值不等於的情況下觸發這個方法
例:@RequestMapping(value = "/login", params = {"id=1","age!=18"}
• 也可以不指定具體的值,直接使用 "paramName" 的格式,代表請求中必須包含參數名爲 paramName 的參數
• 直接使用 “!paramName”格式表示請求不能包含名爲paramName的請求參數

6>.headers屬性
• 請求頭Header中必須包含某些指定的參數值,才能讓該方法處理請求,可以利用這個特性拒絕非指定來源的客戶端的訪問,以加強站點的安全。
例:@RequestMapping(value = "/login", headers = "content-type=text/*")
例:@RequestMapping(value = "/login", headers = {"content-type=text/*","Referer=http://www.buyinplay.com"})

定義Ant風格和帶佔位符的URL

@RequestMapping不僅支持標準的URL,還支持Ant風格和帶{xxx}佔位符的URL,下面的URL都是合法的:

•   /user/*/login:匹配/user/aaa/login,/user/任意字符/login 等
•   /user/**/login:匹配/user/login, /user/aaa/bbb/login 等
•   /user/login??:匹配/user/loginAA, /user/loginbb 等
•   /user/{userId}:匹配/user/123, /user/234 等
•   /user/**/{userId}:匹配/user/aaa/bbb/123,/user/aaa/234等

2.Component註解

Component註解是“Controller註解”、“Service註解”和“Repository註解”的通用註解,可以和它們起到相同的作用(在不清楚使用那個註解的時候,可以統統使用Component,爲了代碼邏輯清晰,還是建議使用具體的註解)。這四個註解都是類級別的, 可以不帶任何參數,也可以帶一個參數,代表bean名字,在進行注入的時候就可以通過名字進行注入了。

![](media/14612091580198/14612489590879.jpg)

使用@Resource或@Autowired註解實現注入
@Resource和@Autowired註解的異同:
@Resource 用於注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName")
@Autowired 用於注入,(srping提供的) 默認按類型裝配,默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設置它的required屬性爲false,例如:@Autowired(required=false) ,如果我們想使用名稱裝配可以結合@Qualifier註解進行使用

一般我會使用@Resource進行注入:

3.Controller註解

類級別的註解,用於聲明控制器類。用法參考“Component註解”。

@Controller 負責註冊一個bean 到spring 上下文中,bean 的ID 默認爲類名稱開頭字母小寫,你也可以自己指定,如下 
方法一: 
@Controller 
public class TestController {} 
 
方法二:            
@Controller("tmpController") 
public class TestController {} 
 

4.Service註解

類級別的註解,用於聲明Service類。用法參考“Component註解”。

5.Repository註解

類級別的註解,用於聲明DAO類。用法參考“Component註解”。

三、其他常用的註解類

1.CookieValue註解

讀取Cookies中的值,並且賦值給變量
有三個屬性 value, required, defaultValue,分別表示Cookie的名字,是否必須有這個Cookie值,如果沒有則使用默認值
不帶任何參數,表示需要的參數名與標註的變量名相同

複製代碼
@RequestMapping("/listone")
public String listone(@CookieValue String goodsName){//不帶任何參數
    return "listone";
}

@RequestMapping("/listtwo")
public String listtwo(@CookieValue("goodsName") String goodsName){//指定Cookie的名字
    return "listtwo";
}

@RequestMapping("/listthree")
public String listthree(@CookieValue(value="goodsName",defaultValue="new",required =false) String goodsName){//指定Cookie的名字,如果沒有這個名字,賦值默認值new
    return "listthree";
}
複製代碼

 

2.PathVariable註解

1>.@PathVariable用於方法中的參數,表示方法參數綁定到地址URL的模板變量。 
例如:

複製代碼
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)  
public String findOwner(@PathVariable String ownerId, Model model) {  
  Owner owner = ownerService.findOwner(ownerId);    
  model.addAttribute("owner", owner);    
  return "displayOwner";  
}  
複製代碼

 


 
2>.@PathVariable用於地址欄使用{xxx}模版變量時使用。 
如果@RequestMapping沒有定義類似"/{ownerId}" ,這種變量,則使用在方法中@PathVariable會報錯。

3.RequestBody註解

4.RequestHeader註解

可以把Request請求header部分的值綁定到方法的參數上

5.RequestMethod註解

6.RequestParam註解

@RequestParam是一個可選參數,例如:@RequestParam("id") 註解,所以它將和URL所帶參數 id進行綁定 。
如果入參是基本數據類型(如 int、long、float 等),URL 請求參數中一定要有對應的參數,否則將拋出 
org.springframework.web.util.NestedServletException 異常,提示無法將 null 轉換爲基本數據類型.

@RequestParam包含3個配置 @RequestParam(required = ,value="", defaultValue = "") 
required :參數是否必須,boolean類型,可選項,默認爲true 
value: 傳遞的參數名稱,String類型,可選項,如果有值,對應到設置方法的參數 
defaultValue:String類型,參數沒有傳遞時爲參數默認指定的值 
 

7.ResponseBody註解

這個註解可以直接放在方法上,表示返回類型將會直接作爲HTTP響應字節流輸出(不被放置在Model,也不被攔截爲視圖頁面名稱)。可以用於ajax。

用於將Controller的方法返回的對象,通過適當的HttpMessageConverter(轉換器)轉換爲指定格式後,寫入到Response對象的body數據區
返回如json、xml等時使用
在springmvc配置文件中通過,給AnnotationMethodHandlerAdapter初始化7個轉換器

  • ByteArranHttpMessageConverter 讀寫二進制數據
  • StringHttpMessageConverter 將請求信息轉換爲字符串
  • ResourceHttpMessageConverter 讀寫org.springframework.core.io.Resource對象
  • SourceHttpMessageConverter 讀寫javax.xml.transform.Source類型的數據
  • XmlAwareFormHttpMessageConverter 處理表單中的XML數據
  • Jaxb2RootElementHttpMessageConverter 通過JAXB2讀寫XML消息,將請求消息轉換到標註XmlRootElement和XmlType的註解類中
  • MappingJacksonHttpMessageConverter 讀寫JSON數據


 

8.SessionAttribute註解

session管理 
如果希望在多個請求之間公用某個模型屬性數據,則可以在控制器類標註一個@SessionAttributes,Spring MVC會將模型中對應的屬性暫存到HttpSerssion中
除了SessionAttributes,還可以直接用原生態的request.getSession()來處理session數據

Spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉存到 session 中,以便下一個請求屬對應的 ModelMap 的屬性列表中還能訪問到這些屬性。這一功能是通過類定義處標註 @SessionAttributes 註解來實現的。@SessionAttributes 只能聲明在類上,而不能聲明在方法上。

複製代碼
 
@SessionAttributes("currUser") // 將ModelMap 中屬性名爲currUser 的屬性 


@SessionAttributes({"attr1","attr2"}) 
@SessionAttributes(types = User.class) 
@SessionAttributes(types = {User.class,Dept.class}) 
@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"}) 
複製代碼

 

複製代碼
@Controller
@RequestMapping(value = "/goods")
@SessionAttributes("rowCount")//代碼中所有名爲rowCount的屬性都會自動存入session中
public class GoodsController {

    @Resource
    GoodsService service;
    
    /**注入語法
    @Autowired
    @Qualifier("goodsService")
    GoodsService service;
     */
    
    @RequestMapping(value = "/list")
    public String helloWorld(HttpServletRequest request){
        String currPageStr = request.getParameter("page");
        int currPage = 1;
        try {
            currPage = Integer.parseInt(currPageStr);
        } catch (Exception e) {
        }
        
        // 獲取總記錄數
        int rowCount = service.getRowCount();//被自動存入session中
        PageParam pageParam = new PageParam();
        pageParam.setRowCount(rowCount);
        if (pageParam.getTotalPage() < currPage) {
            currPage = pageParam.getTotalPage();
        }
        pageParam.setCurrPage(currPage);
        pageParam = service.getGoodsByPage(pageParam);
        
        request.setAttribute("pageParam", pageParam);
        
        return "list";
    }
    
    @RequestMapping("/clearsession")//本方法僅用於演示清除session
    public String doClearSession(String goodsName,SessionStatus status){
        status.setComplete();
        return "list";
    }
}
複製代碼

 

9.Scope("prototype")註解

設定bean的作用域

10.Transactional( rollbackFor={Exception.class})註解

事務管理

11.ModelAttribute註解

1>.應用於方法參數,參數可以在頁面直接獲取,相當於request.setAttribute(,) 
2>.應用於方法,將任何一個擁有返回值的方法標註上 @ModelAttribute,使其返回值將會進入到模型對象的屬性列表中. 
3>.應用於方法參數時@ModelAttribute("xx"),須關聯到Object的數據類型,基本數據類型 如:int,String不起作用 
例如: 
Java代碼  

複製代碼
@ModelAttribute("items")//<——①向模型對象中添加一個名爲items的屬性 

public List<String> populateItems() {  
        List<String> lists = new ArrayList<String>();  
        lists.add("item1");  
        lists.add("item2");  
        return lists;  
}
 
@RequestMapping(params = "method=listAllBoard")  
public String listAllBoard(@ModelAttribute("currUser")User user, 

ModelMap model) {  
        bbtForumService.getAllBoard();  
        //<——②在此訪問模型中的items屬性  
        System.out.println("model.items:" + ((List<String>)

model.get("items")).size());  
        return "listBoard";  
} 
複製代碼

 

 
在 ① 處,通過使用 @ModelAttribute 註解,populateItem() 方法將在任何請求處理方法執行前調用,Spring MVC 會將該方法返回值以“items”爲名放入到隱含的模型對象屬性列表中。 所以在 ② 處,我們就可以通過 ModelMap 入參訪問到 items 屬性,當執行 listAllBoard() 請求處理方法時,② 處將在控制檯打印出“model.items:2”的信息。當然我們也可以在請求的視圖中訪問到模型對象中的 items 屬性。

發佈了13 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章