@RequestParam與@PathVariable的區別

springMVC中的註解@RequestParam與@PathVariable的區別java

一、@PathVariable

@PathVariable是用來得到請求url中的動態參數的node

@PathVariable用於將請求URL中的模板變量映射到功能處理方法的參數上。//配置url和方法的一個關係@RequestMapping("item/{itemId}")
@RequestMapping 來映射請求,也就是經過它來指定控制器能夠處理哪些URL請求,相似於struts的action請求spring

@responsebody表示該方法的返回結果直接寫入HTTP response body中通常在異步獲取數據時使用,在使用@RequestMapping後,返回值一般解析爲跳轉路徑,加上@responsebody後返回結果不會被解析爲跳轉路徑,而是直接寫入HTTP response body中。
好比異步獲取json數據,加上@responsebody後,會直接返回json數據。json

@Pathvariable註解綁定它傳過來的值到方法的參數上
用於將請求URL中的模板變量映射到功能處理方法的參數上,即取出uri模板中的變量做爲參數api

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

@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("參數錯誤");
    }
    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;
  }

二、@RequestParam

在SpringMVC後臺控制層獲取參數的方式主要有兩種:
一種是request.getParameter("name"),另一種是用註解@RequestParam直接獲取
dom

這裏主要講這個註解 @RequestParam異步

接下來咱們看一下@RequestParam註解主要有哪些參數:ui

value:參數名字,即入參的請求參數名字,如username表示請求的參數區中的名字爲username的參數的值將傳入;url

required:是否必須,默認是true,表示請求中必定要有相應的參數,不然將報404錯誤碼;

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

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

@Controller
@RequestMapping("/wx")
public class WxController {

    @Autowired
    private 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);
        }else
            out.print("fail");
        out.flush();
        out.close();
    }
相關文章
相關標籤/搜索