zoukankan      html  css  js  c++  java
  • @RequestParam与@PathVariable的区别

    springMVC中的注解@RequestParam与@PathVariable的区别

    1、@PathVariable

    @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){

    @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;
      }
    

    2、@RequestParam

    在SpringMVC后台控制层获取参数的方式主要有两种:
    一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取

    这里主要讲这个注解 @RequestParam

    接下来我们看一下@RequestParam注解主要有哪些参数:

    value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;

    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();
        }
    
  • 相关阅读:
    [深度概念]·K-Fold 交叉验证 (Cross-Validation)的理解与应用
    [天池竞赛项目]2019菜鸟全球科技挑战赛 —智能体积测量(队员招募)
    [MXNet逐梦之旅]练习一·使用MXNet拟合直线手动实现
    [深度学习工具]·极简安装Dlib人脸识别库
    [数据科学从零到壹]·泰坦尼克号生存预测(数据读取、处理与建模)​​​​​​​
    Java 多线程
    javaAPI中的常用 类 以及接口
    QQ数据库管理
    java 对象和封装
    事务、视图、索引、备份、还原
  • 原文地址:https://www.cnblogs.com/mzdljgz/p/11699186.html
Copyright © 2011-2022 走看看