日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

@RequestParam与@PathVariable的区别

發(fā)布時(shí)間:2024/9/30 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @RequestParam与@PathVariable的区别 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

springMVC中的注解@RequestParam與@PathVariable的區(qū)別

1、@PathVariable

@PathVariable是用來獲得請求url中的動(dòng)態(tài)參數(shù)的

@PathVariable用于將請求URL中的模板變量映射到功能處理方法的參數(shù)上。//配置url和方法的一個(gè)關(guān)系@RequestMapping(“item/{itemId}”)
@RequestMapping 來映射請求,也就是通過它來指定控制器可以處理哪些URL請求,類似于struts的action請求

@responsebody表示該方法的返回結(jié)果直接寫入HTTP response body中一般在異步獲取數(shù)據(jù)時(shí)使用,在使用@RequestMapping后,返回值通常解析為跳轉(zhuǎn)路徑,加上@responsebody后返回結(jié)果不會(huì)被解析為跳轉(zhuǎn)路徑,而是直接寫入HTTP response body中。
比如異步獲取json數(shù)據(jù),加上@responsebody后,會(huì)直接返回json數(shù)據(jù)。

@Pathvariable注解綁定它傳過來的值到方法的參數(shù)上
用于將請求URL中的模板變量映射到功能處理方法的參數(shù)上,即取出uri模板中的變量作為參數(shù)

@ResponseBody
public TbItem getItemById(@PathVariable Long itemId){

@RequestMapping("/zyh/{type}")public String zyh(@PathVariable(value = "type") int type) throws UnsupportedEncodingException {String url = "http://wx.diyfintech.com/zyhMain/" + type;if (type != 1 && type != 2) {throw new IllegalArgumentException("參數(shù)錯(cuò)誤");}String encodeUrl = URLEncoder.encode(url, "utf-8");String redirectUrl = MessageFormat.format(OAUTH_URL, WxConfig.zyhAppId, encodeUrl, "snsapi_userinfo", UUID.randomUUID().toString().replace("-", ""));return "redirect:" + redirectUrl;}

2、@RequestParam

在SpringMVC后臺(tái)控制層獲取參數(shù)的方式主要有兩種:
一種是request.getParameter(“name”),另外一種是用注解@RequestParam直接獲取

這里主要講這個(gè)注解 @RequestParam

接下來我們看一下@RequestParam注解主要有哪些參數(shù):

value:參數(shù)名字,即入?yún)⒌恼埱髤?shù)名字,如username表示請求的參數(shù)區(qū)中的名字為username的參數(shù)的值將傳入;

required:是否必須,默認(rèn)是true,表示請求中一定要有相應(yīng)的參數(shù),否則將報(bào)404錯(cuò)誤碼;

defaultValue:默認(rèn)值,表示如果請求中沒有同名參數(shù)時(shí)的默認(rèn)值,例如:

public List getItemTreeNode(@RequestParam(value=“id”,defaultValue=“0”)long parentId)

@Controller @RequestMapping("/wx") public class WxController {@Autowiredprivate WxService wxService;private static final Log log= LogFactory.getLog(WxController.class);@RequestMapping(value = "/service",method = RequestMethod.GET)public void acceptWxValid(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce,@RequestParam String echostr, HttpServletResponse response) throws IOException {PrintWriter out = response.getWriter();if (SignUtil.checkSignature(signature, timestamp, nonce)) {out.print(echostr);}elseout.print("fail");out.flush();out.close();} 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的@RequestParam与@PathVariable的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。