在spring的controller中,要將參數傳遞到後臺,有兩種方式:第一是將參數作爲url的路徑的一部分傳遞到後臺;第二種是將其作爲參數傳遞到後臺。下面分別來看這兩種方式的實現,如下:
1、url類型:http://localhost:8080/taotaoweb/item/2345354543
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable long itemId){
//此處獲取的itemId就是url地址後面的數值:2345354543
TbItem item=itemService.getItemById(itemId);
return item;
} 【注意】接收參數解決亂碼問題看下面圖片
2、url類型: http://localhost:8096/search/query?q=手機&page=2&rows=10
@RequestMapping(value="/query",method=RequestMethod.GET)
@ResponseBody
public TaotaoResult search(@RequestParam("q")String queryString,
@RequestParam(defaultValue="1")Integer page,
@RequestParam(defaultValue="60")Integer rows){
if (StringUtils.isBlank(queryString)){
return TaotaoResult.build(400, "查詢條件不能爲空!");
}
SearchResult searchResult=null;
try {
queryString=new String(queryString.getBytes("iso8859-1"),"utf-8");
searchResult=searchService.search(queryString, page, rows);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
return TaotaoResult.ok(searchResult);
}