@PathVariable綁定URI模板變量值
@PathVariable是用來獲得請求url中的動態參數的
@PathVariable用於將請求URL中的模板變量映射到功能處理方法的參數上。//配置url和方法的一個關系@RequestMapping("item/{itemId}")
/* @RequestMapping 來映射請求,也就是通過它來指定控制器可以處理哪些URL請求,類似於struts的action請求
* @responsebody表示該方法的返回結果直接寫入HTTP response body中
*一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@responsebody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response *body中。
*比如異步獲取json數據,加上@responsebody后,會直接返回json數據。*
*@Pathvariable注解綁定它傳過來的值到方法的參數上
*用於將請求URL中的模板變量映射到功能處理方法的參數上,即取出uri模板中的變量作為參數
*/
@ResponseBody
public TbItem getItemById(@PathVariable Long itemId){
1 @RequestMapping("/zyh/{type}") 2 public String zyh(@PathVariable(value = "type") int type) throws UnsupportedEncodingException { 3 String url = "http://wx.diyfintech.com/zyhMain/" + type; 4 if (type != 1 && type != 2) { 5 throw new IllegalArgumentException("參數錯誤"); 6 } 7 String encodeUrl = URLEncoder.encode(url, "utf-8"); 8 String redirectUrl = MessageFormat.format(OAUTH_URL, WxConfig.zyhAppId, encodeUrl, "snsapi_userinfo", UUID.randomUUID().toString().replace("-", "")); 9 return "redirect:" + redirectUrl; 10 }
在SpringMVC后台控制層獲取參數的方式主要有兩種:
一種是request.getParameter("name"),另外一種是用注解@RequestParam直接獲取
這里主要講這個注解 @RequestParam
接下來我們看一下@RequestParam注解主要有哪些參數:
value:參數名字,即入參的請求參數名字,如username表示請求的參數區中的名字為username的參數的值將傳入;
required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報404錯誤碼;
defaultValue:默認值,表示如果請求中沒有同名參數時的默認值,例如:
public List<EasyUITreeNode> getItemTreeNode(@RequestParam(value="id",defaultValue="0")long parentId)
1 @Controller 2 @RequestMapping("/wx") 3 public class WxController { 4 5 @Autowired 6 private WxService wxService; 7 private static final Log log= LogFactory.getLog(WxController.class); 8 9 @RequestMapping(value = "/service",method = RequestMethod.GET) 10 public void acceptWxValid(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, 11 @RequestParam String echostr, HttpServletResponse response) throws IOException { 12 PrintWriter out = response.getWriter(); 13 if (SignUtil.checkSignature(signature, timestamp, nonce)) { 14 out.print(echostr); 15 }else 16 out.print("fail"); 17 out.flush(); 18 out.close(); 19 }