Spring MVC常用註解

2021-08-15 17:37:27 字數 1994 閱讀 3225

在springmvc中,@controller用於標記乙個類,將其註冊到spring上下文, 負責處理由dispatcherservlet分發的請求,並將處理結果封裝成乙個model返回給view進行展示。

@controller註解需要被spring所認識,還需要在配置檔案中增加以下配置:

// 通過該配置,spring會掃瞄com

.spring

.controller包下的所有註解

"com.spring.controller"/>

@controller

//控制器,類似於struts的action

public

class

firstcontroller

@requestparam主要功能是輔助控制層獲取到請求中的業務引數,其形式為public string getname(@requestparam("id") string userid),另外,@requestparam能夠將請求中的引數轉換成函式定義中的形參形式。

@pathvariable將請求url中的模板變數對映到方法引數上,即具備從url中獲取動態引數的能力,引數名稱不一致時可參看如下方式:

@responsebody

public string getaddressbyname(@pathvariable("name") string username) else }

@responsebody將controller的方法返回的物件,通過適當的httpmessageconverter轉換為指定格式後,寫入到response物件的body資料區。

@responsebody

public person setperson(@requestbody person person)

@requestheader可以將請求request中的header部分繫結到方法形參上;

@cookievalue可以把request header中關於cookie的值繫結到方法的引數上;

"/getheaderandcookie", method = requestmethod.post)

@responsebody

public

string getheaderandcookie(@requestheader("host") string

header, @cookievalue("name") string cookie)

springmvc 使用@modelattribute在不同方法之間通過model來共享資料,主要有兩種使用方式,一種是標註在方法上,一種是標註在 controller 方法引數上:

@modelattribute作用在方法引數上時,表明該引數可以在model中檢索到,並提取屬性值注入到自定義的方法形參上;

@controller

public

class mycontroller

@modelattribute("userage")

public

intsetage()

public

void

getage(@modelattribute("stringvalue") string name, @modelattribute("userage") int age)

}

執行結果為:

執行 setname 方法

執行 setage 方法

name:zhangsan, age:10

@sessionattributes只能標記在controller類上,指明將model中的哪些屬性是放到session中,可用於在多個請求之間傳遞引數。

SpringMVC常用註解

一,controller 負責註冊乙個bean 到spring 上下文中,bean 的id 預設為類名稱開頭字母小寫。1 在springmvc 的配置檔案中定義mycontroller 的bean 物件。2 在springmvc 的配置檔案中告訴spring 該到 去找標記為 controller ...

SpringMVC常用註解

controller 負責註冊乙個bean 到spring 上下文中 註解為控制器指定可以處理哪些 url 請求 requestbody 該註解用於讀取request請求的body部分資料,使用系統預設配置的httpmessageconverter進行解析,然後把相應的資料繫結到要返回的物件上 再把...

SpringMVC常用註解

controller 註解為控制器指定可以處理哪些 url 請求 requestbody 該註解用於讀取request請求的body部分資料,使用系統預設配置的httpmessageconverter進行解析,然後把相應的資料繫結到要返回的物件上 再把httpmessageconverter返回的物...