springMVC綁定參數及方法返回、json數據交互

Controller參數綁定

1.默認支持參數綁定

示例:

/*
要根據id查詢商品數據,需要從請求的參數中把請求的id取出來。Id應該包含在Request對象中。可以從Request對象中取id。
*/
@RequestMapping("/itemEdit")
	public ModelAndView itemEdit(HttpServletRequest request) {
		//從Request中取id
		String strId = request.getParameter("id");
		Integer id = null;
		//如果id有值則轉換成int類型
		if (strId != null && !"".equals(strId)) {
			id = new Integer(strId);
		} else {
			//出錯
			return null;
		}
		Items items = itemService.getItemById(id);
		//創建ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		//向jsp傳遞數據
		modelAndView.addObject("item", items);
		//設置跳轉的jsp頁面
		modelAndView.setViewName("editItem");
		return modelAndView;
	}

默認支持參數類型

處理器形參中添加如下類型的參數處理適配器會默認識別並進行賦值。

HttpServletRequest 通過request對象獲取請求信息

HttpServletResponse 通過response處理響應信息

HttpSession 通過session對象得到session中存放的對象

Model/ModelMap ModelMap是Model接口的實現類,通過Model或ModelMap向頁面傳遞數據,如下:

//調用service查詢商品信息 相當於放入request域中
Items item = itemService.findItemById(id);
model.addAttribute("item", item);

頁面通過${item.XXXX}獲取item對象的屬性值。

使用Model和ModelMap的效果一樣,如果直接使用Model,springmvc會實例化ModelMap。

如果使用Model則可以不使用ModelAndView對象,Model對象可以向頁面傳遞數據,View對象則可以使用String返回值替代。不管是Model還是ModelAndView,其本質都是使用Request對象向jsp傳遞數據

/*如果使用Model則方法可以改造成:*/
@RequestMapping("/itemEdit")
	public String itemEdit(HttpServletRequest request, Model model) {
		//從Request中取id
		String strId = request.getParameter("id");
		Integer id = null;
		//如果id有值則轉換成int類型
		if (strId != null && !"".equals(strId)) {
			id = new Integer(strId);
		} else {
			//出錯
			return null;
		}
		Items items = itemService.getItemById(id);
		//創建ModelAndView
		//ModelAndView modelAndView = new ModelAndView();
		//向jsp傳遞數據
		//modelAndView.addObject("item", items);
		//設置跳轉的jsp頁面
		//modelAndView.setViewName("editItem");
		//return modelAndView;
	      model.addAttribute("item", items);
		return "editItem";
	}

PS:在springMvc中如果返回字符串,則這個普通字符串就是頁面路徑名稱

2.綁定簡單類型

當請求的參數名稱和處理器形參名稱一致時會將請求參數與形參進行綁定

@RequestMapping("/itemEdit")
	public String itemEdit(Integer id, Model model) {
		Items items = itemService.getItemById(id);
		//向jsp傳遞數據
		model.addAttribute("item", items);
		//設置跳轉的jsp頁面
		return "editItem";
	}

PS:參數類型推薦使用包裝數據類型,因爲基礎數據類型不可以爲null

@​​​RequestParam 

使用@RequestParam常用於處理簡單類型的綁定。

value:參數名字,即傳入參的請求參數名字,如value=“item_id”表示請求的參數區中的名字爲item_id的參數的值將傳入;

required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報;

TTP Status 400 - Required Integer parameter 'XXXX' is not present

defaultValue:默認值,表示如果請求中沒有同名參數時的默認值

定義如下:

public String editItem(@RequestParam(value="item_id",required=true) String id) {

}

形參名稱爲id,但是這裏使用value=" item_id"限定請求的參數名爲item_id,所以頁面傳遞參數的名必須爲item_id。

注意:如果請求參數中沒有item_id將拋出異常:

HTTP Status 400 - Required Integer parameter 'item_id' is not present

這裏通過required=true限定item_id參數爲必需傳遞,如果不傳遞則報400錯誤,可以使用defaultvalue設置默認值,即使required=true也可以不傳item_id參數值

綁定pojo類型

請求的參數名稱和pojo的屬性名稱一致,會自動將請求參數賦值給pojo的屬性。

@RequestMapping("/updateitem")
	public String updateItem(Items items) {
		itemService.updateItem(items);
		return "success";
	}

注意:提交的表單中不要有日期類型的數據,否則會報400錯誤。如果想提交日期類型的數據需要用到後面的自定義參數綁定的內容。

3.高級參數綁定

(1)接收數組

Controller方法中可以用String[]接收,或者pojo的String[]屬性接收。兩種方式任選其一即可。
定義如下:

@RequestMapping("/queryitem")
	public String queryItem(QueryVo queryVo, String[] ids) {
		System.out.println(queryVo.getItems().getName());
		System.out.println(queryVo.getItems().getPrice());
		System.out.println(ids.toString());
		return null;
	}

(2)接收List

接收List類型的數據必須是pojo的屬性,既使用對象內的List屬性接收。方法的形參爲List類型無法正確接收到數據。

public class QueryVo{
    private List<Items> itemsList;
}
------------
@RequestMapping("/queryitem")
	public String queryItem(QueryVo queryVo) {
		System.out.println(queryVo.getItemsList().size());
		return null;
	}

controller方法返回值

1.返回ModelAndView

controller方法中定義ModelAndView對象並返回,對象中可添加model數據、指定view

2.返回void

在controller方法形參上可以定義request和response,使用request或response指定響應結果:

1、使用request轉向頁面,如下: request 帶參

request.getRequestDispatcher("url").forward(request, response);

2、也可以通過response頁面重定向: response 不帶參

response.sendRedirect("url")

3、也可以通過response指定響應結果,例如響應json數據如下:

response.setCharacterEncoding("utf-8");//設置返回編碼格式

response.setContentType("application/json;charset=utf-8");

response.getWriter().write("json串");

response.setCharacterEncoding("utf-8");//設置返回編碼格式

response.setContentType("application/json;charset=utf-8");

response.getWriter().write("json串");

3.返回字符串

controller方法返回字符串可以指定邏輯視圖名,通過視圖解析器解析爲物理視圖地址。

//指定邏輯視圖名,經過視圖解析器解析爲jsp物理路徑:/WEB-INF/jsp/item/editItem.jsp

return "item/editItem";

4.Redirect重定向

Controller方法返回結果重定向到一個url地址,如下商品修改提交後重定向到商品查詢方法,參數無法帶到商品查詢方法中

//重定向到queryItem.action地址,request無法帶過去
return "redirect:queryItem.action";

redirect方式相當於“response.sendRedirect()”,轉發後瀏覽器的地址欄變爲轉發後的地址,因爲轉發即執行了一個新的request和response。

由於新發起一個request原來的參數在轉發時就不能傳遞到下一個url,如果要傳參數可以/item/queryItem.action後邊加參數,如下:

/item/queryItem?...&..

5.forward轉發

controller方法執行後繼續執行另一個controller方法,如下商品修改提交後轉向到商品修改頁面,修改商品的id參數可以帶到商品修改方法中。

//結果轉發到editItem.action,request可以帶過去
return "forward:editItem.action";

forward方式相當於“request.getRequestDispatcher().forward(request,response)”,轉發後瀏覽器地址欄還是原來的地址。轉發並沒有執行新的request和response,而是和轉發前的請求共用一個request和response。所以轉發前請求的參數在轉發後仍然可以讀取到。

 

Forward:後面以/開始是絕對路徑,絕對路徑是從項目名稱開始計算

Forward:後面不以/開始是相對路徑,相對路徑是相對於當前路徑

json數據交互

1. @RequestBody

作用:

@RequestBody註解用於讀取http請求的內容(字符串),通過springmvc提供的HttpMessageConverter接口將讀到的內容轉換爲json、xml等格式的數據並綁定到controller方法的參數上。

List.action?id=1&name=zhangsan&age=12

本例子應用:

@RequestBody註解實現接收http請求的json數據,將json數據轉換爲java對象

2. @ResponseBody 

Json字符串和java對象之間的傳遞

作用:

該註解用於將Controller的方法返回的對象,通過HttpMessageConverter接口轉換爲指定格式的數據如:json,xml等,通過Response響應給客戶端

本例子應用:

@ResponseBody註解實現將controller方法返回對象轉換爲json格式響應給客戶端

// 商品修改提交json信息,響應json信息
@RequestMapping("/sendJson")
@ResponseBody//可以返回json字符串自動轉換,直接返回
public  Items sendJson(@RequestBody Items items) throws Exception {
		//第二個RequestBody可以接收ajax提交的json字符串自動封裝爲Items對象
        System.out.println(items);
		//itemService.saveItem(items);
		return items;//在傳回ajaxdata

	}

 

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