Spring MVC(二) 基于注解的控制器

1、@Controller

@Controller
public class UserController {
.......
.......

}

和Struts1一樣,Spring的Controller是Singleton的。這就意味著會(huì)被多個(gè)請(qǐng)求線(xiàn)程共享。因此,我們將控制器設(shè)計(jì)成無(wú)狀態(tài)類(lèi)。
2、@RequestMapping
① 在類(lèi)前面定義,則將url和類(lèi)綁定;(如果該類(lèi)里只有單個(gè)方法的話(huà)可以這樣寫(xiě),訪(fǎng)問(wèn)該地址直接調(diào)用該方法)

示例代碼如下:

@RequestMapping("/queryuser")
public class UserController {
......
......
}

② 在方法前面定義,則將url和類(lèi)的方法綁定。

示例代碼如下:

@Controller
public class UserController {

    @RequestMapping("/queryuser")
    public Object queryUserList(HttpServletRequest request, HttpServletResponse response) {
.....
.....
    }
}

3、@RequestParam

A) 常用來(lái)處理簡(jiǎn)單類(lèi)型的綁定,通過(guò)Request.getParameter() 獲取的String可直接轉(zhuǎn)換為簡(jiǎn)單類(lèi)型的情況( String--> 簡(jiǎn)單類(lèi)型的轉(zhuǎn)換操作由ConversionService配置的轉(zhuǎn)換器來(lái)完成);因?yàn)槭褂胷equest.getParameter()方式獲取參數(shù),所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;

B)用來(lái)處理Content-Type: 為 application/x-www-form-urlencoded編碼的內(nèi)容,提交方式GET、POST;

GET模式下,這里使用了@PathVariable綁定輸入?yún)?shù),非常適合Restful風(fēng)格。因?yàn)殡[藏了參數(shù)與路徑的關(guān)系,可以提升網(wǎng)站的安全性,靜態(tài)化頁(yè)面,降低惡意攻擊風(fēng)險(xiǎn)。
POST模式下,使用@RequestBody綁定請(qǐng)求對(duì)象,Spring會(huì)幫你進(jìn)行協(xié)議轉(zhuǎn)換,將Json、Xml協(xié)議轉(zhuǎn)換成你需要的對(duì)象。
C) 該注解有兩個(gè)屬性: value、required; value用來(lái)指定要傳入值的id名稱(chēng),required用來(lái)指示參數(shù)是否必須綁定;

/**
    * 刪除代理商操作
    * **/
   @RequestMapping(value = "/del")
   @ResponseBody
   public MsgBean deleteAgents(@RequestParam("ids")String ids[]){
       MsgBean msg = null;
       try {
           msg = agentsService.delAgents(ids);
       } catch (Exception e) {
           logger.error("代理商刪除操作出錯(cuò)..." + e.getMessage());
           throw new BusinessException(e.getMessage());
       }
       return msg;
   }

@PathVaribale

image.png

4、@ResponseBody

作用:

該注解用于將Controller的方法返回的對(duì)象,通過(guò)適當(dāng)?shù)腍ttpMessageConverter轉(zhuǎn)換為指定格式后,寫(xiě)入到Response對(duì)象的body數(shù)據(jù)區(qū)。

使用時(shí)機(jī):

返回的數(shù)據(jù)不是html標(biāo)簽的頁(yè)面,而是其他某種格式的數(shù)據(jù)時(shí)(如json、xml等)使用;

代碼如上

5、@RequestBody

作用:

i) 該注解用于讀取Request請(qǐng)求的body部分?jǐn)?shù)據(jù),使用系統(tǒng)默認(rèn)配置的HttpMessageConverter進(jìn)行解析,然后把相應(yīng)的數(shù)據(jù)綁定到要返回的對(duì)象上;

ii) 再把HttpMessageConverter返回的對(duì)象數(shù)據(jù)綁定到 controller中方法的參數(shù)上。

使用時(shí)機(jī):

@RequestBody主要用來(lái)接收前端傳遞給后端的json字符串中的數(shù)據(jù)的(請(qǐng)求體中的數(shù)據(jù)的);

GET方式無(wú)請(qǐng)求體,所以使用@RequestBody接收數(shù)據(jù)時(shí),前端不能使用GET方式提交數(shù)據(jù),而是用POST方式進(jìn)行提交。

在后端的同一個(gè)接收方法里,@RequestBody 與@RequestParam()可以同時(shí)使用,@RequestBody最多只能有一個(gè),而@RequestParam()可以有多個(gè)。

注:一個(gè)請(qǐng)求,只有一個(gè)RequestBody;一個(gè)請(qǐng)求,可以有多個(gè)RequestParam

6、@SessionAttributes

@SessionAttributes:

該注解用來(lái)綁定HttpSession中的attribute對(duì)象的值,便于在方法中的參數(shù)里使用。

該注解有value、types兩個(gè)屬性,可以通過(guò)名字和類(lèi)型指定要使用的attribute 對(duì)象;

@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"})   //將ModelMap中屬性名字為u、a的再放入session中。這樣,request和session中都有了。
publicclass UserController  {
    @RequestMapping(params="method=list")
    public String list(ModelMap map) {              
  System.out.println("HelloController.handleRequest()");
    map.addAttribute("u","users");  //將u放入request作用域中,這樣轉(zhuǎn)發(fā)頁(yè)面也可以取到這個(gè)數(shù)據(jù)。
       return"index";
    }
}

index里面的代碼

<body>
   <h1>${requestScope.u.uname}</h1>
   <h1>${sessionScope.u.uname}</h1>
  </body>

7、@ModelAttribute

該注解有兩個(gè)用法,一個(gè)是用于方法上,一個(gè)是用于參數(shù)上;

用于方法上時(shí): 通常用來(lái)在處理@RequestMapping之前,為請(qǐng)求綁定需要從后臺(tái)查詢(xún)的model;

用于參數(shù)上時(shí): 用來(lái)通過(guò)名稱(chēng)對(duì)應(yīng),把相應(yīng)名稱(chēng)的值綁定到注解的參數(shù)bean上;要綁定的值來(lái)源于:

A) @SessionAttributes 啟用的attribute 對(duì)象上;

B) @ModelAttribute 用于方法上時(shí)指定的model對(duì)象;

C) 上述兩種情況都沒(méi)有時(shí),new一個(gè)需要綁定的bean對(duì)象,然后把request中按名稱(chēng)對(duì)應(yīng)的方式把值綁定到bean中。

用到方法上@ModelAttribute的示例代碼:

@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
}  

這種方式實(shí)際的效果就是在調(diào)用@RequestMapping的方法之前,為request對(duì)象的model里put(“account”, Account);

用在參數(shù)上的@ModelAttribute示例代碼:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
public String processSubmit(@ModelAttribute Pet pet) {  
     
}

首先查詢(xún) @SessionAttributes有無(wú)綁定的Pet對(duì)象,若沒(méi)有則查詢(xún)@ModelAttribute方法層面上是否綁定了Pet對(duì)象,若沒(méi)有則將URI template中的值按對(duì)應(yīng)的名稱(chēng)綁定到Pet對(duì)象的各屬性上。

@ModelAttribute可以和@SessionAttributes配合在一塊使用??梢酝ㄟ^(guò)ModelMap中屬性的值通過(guò)該注解自動(dòng)賦給指定變量。

示例代碼如下:

@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"}) 
publicclass UserController  {
   
    @RequestMapping(params="method=list1")
    public String list1(ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       map.addAttribute("u","光頭強(qiáng)");
       return"index";
    }
   
    @RequestMapping(params="method=list2")
public String list2(@ModelAttribute("u")String username ,ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       System.out.println(username );
       return"index";
    }
   
}

上述先調(diào)用list1方法,再調(diào)用list2方法。
轉(zhuǎn)載至https://www.cnblogs.com/wzqkalil/p/5328100.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容