1. 程式人生 > >【SpringMVC】SpringMVC常用註解

【SpringMVC】SpringMVC常用註解

[email protected]

       引用包:org.springframework.stereotype.Controller,使用Controller標識他是一個控制器

【2.@RequestMapping】

①實現對註解方法和url進行對映,一個方法對應一個URL,進行處理器對映使用

②實現窄化請求對映,在Controller類上加上RequestMapping註解,即可將該類下所有的URL路徑歸位配置的路徑。③也可以限制請求方法,限制為get提交或post提交等

RequestMapping註解有六個屬性:

  • value:指定請求的實際地址。
  • method:指定請求的method型別,GETPOST等。
  • consumes:指定處理請求的提交內容型別(Content-Type),例如application/jsontext/html
  • produces:指定返回的內容型別,當request請求頭中的Accept型別中包含該指定型別才返回。
  • params:指定request中必須包含某些引數數值。
  • headers:指定request中必須包含某些指定的header值。

示例:

窄化請求對映:

/**
 * 商品的Controller
 * 
 * @author happy
 *
 */
@Controller
// 為了對URL進行分類管理,可以在這裡定義根路徑,最終訪問的路徑就是配置檔案中的路徑加上這裡配置的路徑再加上方法中的自路徑
@RequestMapping("/items")
public class ItemsController {
}

限制請求方法:

// 開啟修改 頁面
@RequestMapping(value = "/editItems", method = { RequestMethod.POST,
		RequestMethod.GET })
public String editItems(Model model,
		@RequestParam(value = "id", required = true) Integer items_id)
		throws Exception {
	// 呼叫service根據商品ID查詢商品資訊
	ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
	// 通過形參中的model,將model資料傳到頁面,相當於ModelAndView.addObject方法
	model.addAttribute("items", itemsCustom);
	return "items/editItems";

}

【3.@Autowired】

       可以對成員變數、方法和建構函式進行標註,來完成自動裝配的工作。

@Autowired
private ItemsServiceitemsService;

[email protected]

       常用於處理簡單型別的繫結,主要用於在springmvc後臺控制層獲取引數。有三個常用引數:

  • value:請求引數名字,如value="item_id",表示請求的引數區中的名字為item_id的引數的值將傳入;
  • defaultValue:表示設定預設值。
  • required:是否必須,預設是true,表示請求中一定要有相應的引數,否則將報錯:Required Integer parameter'***'is not present

[email protected]

        該註解用於springmvc的校驗,和BindingResultbindingResult配對出現

Controller程式碼:

// 商品資訊修改提交
// 在需要校驗的pojo前邊新增@Validated,在需要校驗的pojo後邊新增BindingResult
// bindingResult接收校驗出錯資訊
// 注意:@Validated和BindingResult BindingResult是配對出現的,並且形參順序是固定的
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(
		Model model,
		HttpServletRequest request,
		Integer id,
		@ModelAttribute("items") @Validated(value = { ValidGroup1.class }) ItemsCustom itemsCustom,
		BindingResult bindingResult, MultipartFile items_pic)
		throws Exception {

	// 獲取校驗錯誤資訊
	if (bindingResult.hasErrors()) {
		// 輸出錯誤資訊
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		for (ObjectError objectError : allErrors) {
			// 輸出錯誤資訊
			System.out.println(objectError.getDefaultMessage());
		}
		// 將錯誤資訊傳到頁面
		model.addAttribute("allErrors", allErrors);

		// 可以直接使用model將提交pojo回顯到頁面
		model.addAttribute("items", itemsCustom);
		// 出錯重新到商品修改頁面
		return "items/editItems";
	}

	// 呼叫service更新商品資訊,頁面徐亞將商品資訊傳導此方法
	itemsService.updateItems(id, itemsCustom);
	return "success";
}

[email protected]

       用於不同的模型和控制器之間共享資料。當@ModelAttribute 標記在方法上的時候,該方法將在處理器方法執行之前執行,然後把返回的物件存放在 session 或模型屬性中,屬性名稱可以使用@ModelAttribute(“attributeName”) 在標記方法的時候指定,若未指定,則使用返回型別的類名稱(首字母小寫)作為屬性名稱。

// 商品分類
	//itemtypes表示最終將方法返回值放在request中的key
	@ModelAttribute("itemtypes")
	public Map<String, String> getItemTypes() {

		Map<String, String> itemTypes = new HashMap<String, String>();
		itemTypes.put("101", "數碼");
		itemTypes.put("102", "母嬰");

		return itemTypes;
	}

【7.@RequestBody@ResponseBody】

        @RequestBody接收的是一個Json物件的字串,將json串轉成java物件,

該註解常用來處理Content-Type:不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;

@ResponseBody是將json串轉成Java物件

示例:

jsp程式碼:

<inputtype="button" onclick="requestJson()"value="請求json,輸出是json"/>

JS程式碼:

//請求json,輸出是json
function requestJson(){
	
	$.ajax({
		type:'post',
		url:'${pageContext.request.contextPath }/requestJson.action',
		contentType:'application/json;charset=utf-8',
		//資料格式是json串,商品資訊
		data:'{"name":"手機","price":999}',
		success:function(data){//返回json結果
			alert(data.name);
		}
		
	});	
}

Controller程式碼:

// 請求json,輸出json
// @RequestBody將請求的商品資訊的json串轉成itemsCustom物件
// @ResponseBody將itemsCustom轉成json輸出
@RequestMapping("/requestJson")
public @ResponseBody ItemsCustom requestJson(
		@RequestBody ItemsCustom itemsCustom) {
	return itemsCustom;
}

結果:


[email protected]

        是用來獲得請求url中的動態引數的。

示例:

// 查詢商品資訊,輸出json
// 如果佔位符中的名稱和形參名一致,在@PathVariable可以不指定名稱
@RequestMapping("/itemsView/{id}")
public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id)
		throws Exception {
	// 呼叫service查詢商品資訊
	ItemsCustom itemsCustom = itemsService.findItemsById(id);
	return itemsCustom;
}

[email protected]

       用於dao層的註解,在dao的實現類daoImpl類上註解。

[email protected]

       用於標記需要存放到session中的資料。

[email protected]

       用於把Request請求header部分的值繫結到方法的引數上。

       Request請求的header包含的資訊有:有很多,這裡就舉個例子。

例如header包含Accept,可以指定客戶端能夠接受的內容型別。(示例: text/plain, text/html);還有host,可以指定請求的額伺服器的域名和埠號(示例:localhost:8080  )。使用如下:

Publicvoid Test(@RequestHeader("Host")String url){}

[email protected]

       @CookieValue註解可以把RequestHeader中關於cookie的值,繫結到方法的引數上。(類似於@RequestHeader的用法)