zoukankan      html  css  js  c++  java
  • spring mvc获取路径参数的几种方式

    一、从视图向controller传递值,  controller <--- 视图

    1、通过@PathVariabl注解获取路径中传递参数 (参数会被复制到路径变量)

     @RequestMapping(value = "/{id}/{str}") 
         public ModelAndView helloWorld(@PathVariable String id, 
                 @PathVariable String str) { 
             System.out.println(id); 
             System.out.println(str); 
             return new ModelAndView("/helloWorld"); 
         }
    

    2、  
     
    1)简单类型,如int, String, 应在变量名前加@RequestParam注解,
    例如:

    @RequestMapping("hello3")
           public String hello3( @RequestParam("name" ) String name,
                                   @RequestParam("hobby" ) String hobby){
                System. out.println("name=" +name);
                System. out.println("hobby=" +hobby);      
                 return "hello" ;
          }
    

      但这样就要求输入里面必须有这两个参数了,可以用required=false来取消,例如:
    @RequestParam(value="name",required=false) String name
    但经测试也可以完全不写这些注解,即方法的参数写String name,效果与上面相同。

    2)对象类型:

    @RequestMapping("/hello4" )
           public String hello4(User user){
                System.out.println("user.getName()=" +user.getName());
                System.out.println("user.getHobby()=" +user.getHobby());
                return "hello";
          }
    

      Spring MVC会按:
         “HTTP请求参数名=  命令/表单对象的属性名”
        的规则自动绑定请求数据,支持“级联属性名”,自动进行基本类型数据转换。
    此外,还可以限定提交方法为POST,即修改方法的@RequestMapping注解为
    @RequestMapping(value="/hello4",method=RequestMethod.POST)

  • 相关阅读:
    思考:缓存的使用?灵活运用?
    线程和并发--基础
    java基础--方法
    java基础--数组
    数据结构复习笔记
    asp搭建网站
    转换磁盘格式
    cypress 与其他测试框架的区别
    cypress启动时报错file already exists,文件已经存在解决办法
    cypress的安装
  • 原文地址:https://www.cnblogs.com/skyLogin/p/6598389.html
Copyright © 2011-2022 走看看