zoukankan      html  css  js  c++  java
  • 【转】SpringBoot处理url中的参数的注解

    1.介绍几种如何处理url中的参数的注解

     @PathVaribale  获取url中的数据

     @RequestParam  获取请求参数的值

     @GetMapping  组合注解,是 @RequestMapping(method = RequestMethod.GET) 的缩写

    (1)PathVaribale 获取url中的数据

      看一个例子,如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:

    复制代码
    1 @RestController
    2 public class HelloController {
    3     @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
    4     public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
    5         return "id:"+id+" name:"+name;
    6     }
    7 }
    复制代码

    在浏览器中 输入地址: localhost:8080/hello/100/helloworld 然后会在html页面上打印出:

    id:81 

      同样,如果我们需要在url有多个参数需要获取,则如下代码所示来做就可以了。

    复制代码
    1 @RestController
    2 public class HelloController {
    3     @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
    4     public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
    5         return "id:"+id+" name:"+name;
    6     }
    7 }
    复制代码

    在浏览器中输入地址: localhost:8080/hello/100/helloworld 然后会在html页面上打印出:

     id:100 name:helloworld 

      以上,通过 @PathVariable 注解来获取URL中的参数时的前提条件是我们知道url的格式时怎么样的。
      只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。
      一般情况下,url的格式为: localhost:8080/hello?id=98 ,这种情况下该如何来获取其id值呢,这就需要借助于 @RequestParam 来完成了

      

    2.@RequestParam 获取请求参数的值

      例如:

    复制代码
    @RestController
    public class HelloController {
        @RequestMapping(value="/hello",method= RequestMethod.GET)
        public String sayHello(@RequestParam("id") Integer id){
            return "id:"+id;
        }
    }
    复制代码

    在浏览器中输入地址: localhost:8080/hello?id=1000 ,可以看到如下的结果:

     id:1000 

    当我们在浏览器中输入地址: localhost:8080/hello?id  ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:

     id:null 

    但是,当我们在浏览器中输入地址: localhost:8080/hello  ,即不输入id参数,则会报如下错误:

     whitelable Error Page错误 

     @RequestParam 注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,具体代码如下:

    复制代码
    1 @RestController
    2 public class HelloController {
    3     @RequestMapping(value="/hello",method= RequestMethod.GET)
    4     //required=false 表示url中可以不穿入id参数,此时就使用默认参数
    5     public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
    6         return "id:"+id;
    7     }
    8 }
    复制代码

    如果在url中有多个参数,即类似于 localhost:8080/hello?id=98&&name=helloworld 这样的url,同样可以这样来处理。具体代码如下:

    复制代码
    1 @RestController
    2 public class HelloController {
    3     @RequestMapping(value="/hello",method= RequestMethod.GET)
    4     public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){
    5         return "id:"+id+ " name:"+name;
    6     }
    7 }
    复制代码

    在浏览器中的测试结果如下: localhost:8080/hello?id=1000&name=helloworld 地址,就会显示下面的内容:
     id:1000 name:helloworld 

    3.@GetMapping 组合注解

     @GetMapping 是一个组合注解,是 @RequestMapping(method = RequestMethod.GET) 的缩写。该注解将HTTP Get 映射到 特定的处理方法上。
    即可以使用 @GetMapping(value = “/hello”) 来代替 @RequestMapping(value=”/hello”,method= RequestMethod.GET) 。即可以让我们精简代码。

    复制代码
    1 @RestController
    2 public class HelloController {
    3 //@RequestMapping(value="/hello",method= RequestMethod.GET)
    4 @GetMapping(value = "/hello")
    5 //required=false 表示url中可以不穿入id参数,此时就使用默认参数
    6 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
    7     return "id:"+id;
    8        }
    9   }
    复制代码

    4.PostMapping组合注解:

      方法同GetMapping

    其它:

    SpringMVC接收参数分情况有很多方式,用于绑定参数或者接收参数的注解有很多,当然springboot也一样,因为SpringBoot用的就是SpringMVC。我们大致可以根据它们处理request的方式不同,分成四类。

    @RequestParam ,@RequestBody //处理request body部分的注解
    @PathVariable //处理request 动态url的(resultful风格)注解
    @RequestHeader @CookieValue //处理request头部信息的注解
    @SessionAttributes @ModelAttributes //处理attributesd的注解

    1,通常情况下,我们用名字匹配原则就可以接收参数

    直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交。

    url为:http:127.0.0.1/login?userName=1111&pwd=2222

    
    @RequestMapping(“/login”)
    public void login(String loginname,String pwd)
    {
    system.out.println(loginname+“:”+pass);
    }

    或者
    通过一个bean来接收,post方式和get方式都可以。

    public Class User{
    private String userName;
    private String pwd;
    //setting和getting方法
    }
    @requestMapping(“/login”)
    public void login(User user){
      System.out.println(userName+“ :”+pwd);
    }

    当然可以通过HttpServletRequest接收,post方式和get方式都可以。

    @RequestMapping(“/login”)
    public String addUser2(HttpServletRequest request) {
    String username=request.getParameter(“username”);
    String password=request.getParameter(“pwd”);
    System.out.println(“username is:”+username);
    System.out.println(“password is:”+password);
    return “demo/index”;
    }

    2.@RequestParam注解用于将指定的请求参数赋值给方法的参数。
    虽然第一种方法可以,但是方法的参数要跟前端一样,这样不方便,而且为空时不能设置默认值,于是有了@RequestParam注解

    属性类型是否必要说明
    name String 指定绑定请求的参数
    value String name属性的别名,就是方法的参数名
    reuuired boolean 指定方法是否绑定,如果绑定,方法参数必要有值
    defaultValue String 如果请求没有传递值,而给方法参数默认的值
    @RequestMapping(“/login”)
    public void login(@RequestParam(name=“loginname”) String loginname,@RequestParam(name=“passname”,value=“pass”) String pass)
    {
    system.out.println(loginname+“:”+pass);
    }

    3.@RequestBody将请求体中的JSON字符串绑定到相应的bean上,当然,也可以将其分别绑定到对应的字符串上。
    上面都是普通的字段,但是json字符串怎么接收呢,于是有了@RequestBody。将前台使用get和post方式提交数据时,数据编码格式由请求头ContentType指定,可以分这几种情况:
    application/x-www-form-urlencoded:可以用@RequestParam很方便的接收,当然@RequestBody也可以
    application/json或者application/xml:只能用@RequestBody接收
    multipart/form-data:.@RequestBody不能接收这种

    @requestMapping(“/login”)
    public void login(@requestBody String userName,@requestBody String pwd){
      System.out.println(userName+“ :”+pwd);
    }
    $.ajax({
    url:“/login”,
    type:“POST”,
    data:‘{“userName”:”admin”,”pwd”,”admin123”}’,
    content-type:“application/json charset=utf-8”, //必须application/json
    success:function(data){
    alert(“request success ! “);
    }
    });

    这种情况是将JSON字符串中的两个变量的值分别赋予了两个字符串,但是如果很多呢,这样我们就可以@RequestBody和JavaBean来接收

    public Class User{
    private String userName;
    private String pwd;
    //setting和getting方法
    }
    @requestMapping(“/login”)
    public void login(@requestBody User user){
      System.out.println(userName+“ :”+pwd);
    }
    $.ajax({
    url:“/login”,
    type:“POST”,
    data:‘{“userName”:”admin”,”pwd”,”admin123”}’,
    content-type:“application/json charset=utf-8”,
    success:function(data){
    alert(“request success ! “);
    }
    });

    说明:

    @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);

    GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。

    在后端的同一个接收方法里,@RequestBody 与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。

    注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam

    4.@PathVariable注解可以方便的得到url中的动态参数,@PathVariable注解只有一个属性name,用来绑定参数的名称,如果不填,则默认是方法的参数名。

    @requestMapping(“/login/{userId}”)
    public void login(@PathVariable String userId){
      System.out.println(userId);
    }
    @requestMapping(“/login/{userId}”)
    public void login(@PathVariable(name=“userId”) String username){
      System.out.println(username);
    }

    说明:
    可以在@RequestMapping注解中用{}来表明它的变量部分,这种被称为resultful风格,例如:

    @RequestMapping(“/login/{userId}”)

    这里{userId}就是我们定义的变量规则,userId是变量的名字,那么这个URL路由可以匹配下列任意URL并进行处理:

    /login/tianmaying
    /login/ricky
    /login/tmy1234

     

    注意:在默认情况下,变量中不可以包含URL的分隔符/,例如路由不能匹配/users/tianmaying/ricky,即使你认为tianmaying/ricky是一个存在的用户名

    5.@CookieValue 用于将请求的cookie数据映射到方法的参数上。

    属性类型是否必要说明
    name String 指定绑定请求的参数
    value String name属性的别名,就是方法的参数名
    reuuired boolean 指定方法是否绑定,如果绑定,方法参数必要有值
    defaultValue String 如果请求没有传递值,而给方法参数默认的值
    @RequestMapping(“/login”)
    public void login(@CookieValue(value=“NAME”,defaultValue “”) String sessionId)
    {
    system.out.println(sessionId);
    }

    上面会把NAME的值给sessionId,如果没有这个cookie,则默认为空。

    对ajax请求中的json字符串的一些补充:

    @RequestBody 接收客户端发送的ajax请求中的json字符串,后端自动转换为User对象

    前端

    var username = $('#username').val();
    var password = $('#password').val();
    var data = {username : username , password: password};
    if(username != "" && password != ""){
        $.ajax({
            type: "post",
            url: "${pageContext.request.contextPath}/user/login",
            dataType: "json",
            contentType: "application/json",//设置类型为json
            data: JSON.stringify(data),//数据要经过这个进行处理转为json字符串
            //JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串
            success: function (msg) {
                //处理
            },
            error:function () {
                alert("错误")
            }
        });
    }else {
        alert('请输入账号密码')
    }

    controller

        @PostMapping(value = "/login")
        @ResponseBody
        public String login(@RequestBody User pass_user,HttpSession session){
            User user = userService.login(pass_user.getUsername(), pass_user.getPassword());
    
            if (user != null) {
                session.setAttribute("user",user);
                return "1";
            }
            return "0";
        }

    也可以用map接收

        @PostMapping(value = "/login")
        @ResponseBody
        public String login(@RequestBody Map<String,Object> pass_user,HttpSession session){
            User user = userService.login(pass_user.get("username").toString(), pass_user.get("password").toString());
    
            if (user != null) {
                session.setAttribute("user",user);
                return "1";
            }
            return "0";
        }

    总结:

    1.json字符串和JavaBean对象互相转换的过程中,需要使用jackson的jar包

    2.前端Ajax默认使用json对象的形式上传数据   可以修改contenType  =“application/json” 上传json字符串类型

    maven加入的依赖

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.0</version>
    </dependency>
     

    1、以RequestParam接收

    前端传来的是json数据不多时:[id:id],可以直接用@RequestParam来获取值

    @Autowired
    private AccomodationService accomodationService;
    
    @RequestMapping(value = "/update")
    @ResponseBody
    public String updateAttr(@RequestParam ("id") int id) {
        int res=accomodationService.deleteData(id);
        return "success";
    }

    2、以实体类方式接收

    前端传来的是一个json对象时:{【id,name】},可以用实体类直接进行自动绑定

    @Autowired
    private AccomodationService accomodationService;
    
        @RequestMapping(value = "/add")
        @ResponseBody
        public String addObj(@RequestBody Accomodation accomodation) {
            this.accomodationService.insert(accomodation);
            return "success";
        }

    3、以Map接收

    前端传来的是一个json对象时:{【id,name】},可以用Map来获取

    @Autowired
    private AccomodationService accomodationService;
    
    @RequestMapping(value = "/update")
    @ResponseBody
    public String updateAttr(@RequestBody Map<String, String> map) {
        if(map.containsKey("id"){
            Integer id = Integer.parseInt(map.get("id"));
        }
        if(map.containsKey("name"){
            String objname = map.get("name").toString();
        }
        // 操作 ...
        return "success";
    }

    4、以List接收

    当前端传来这样一个json数组:[{id,name},{id,name},{id,name},...]时,用List<E>接收

    @Autowired
    private AccomodationService accomodationService;
    
    @RequestMapping(value = "/update")
    @ResponseBody
    public String updateAttr(@RequestBody List<Accomodation> list) {
        for(Accomodation accomodation:list){
            System.out.println(accomodation.toString());
        }
        return "success";
    }
     

    SpringMVC接收List型参数

    1、controller

    @RequestMapping("/postList")
        @ResponseBody
        public String postList(@RequestBody List<TestL> testL){
            System.out.println(testL);
            return null;
        
        }

    需要注意点:参数前面必须有注解 @RequestBody

    2、ajax请求

    var testList=[];
    var user={};
    user.id=1;
    user.name='jack';
    testList.push(user);
    var user2={};
    user2.id=2;
    user2.name='tom';
    testList.push(user2);
    $.ajax({
        // headers必须添加,否则会报415错误
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
      type: 'POST',
      dataType: "json", //表示返回值类型,不必须
      data: JSON.stringify(testList),
      url: '/test/postList',
      success: function(){
          alert('success');
      }
      
    });

    需要注意点:1、参数是数组类型

          2、传入data时,转换 JSON.stringify(testList)

          3、必须有headers: {

                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }

    最后再看下TestL类,没有特别之处(不用包装)。
    public class TestL {
        private Integer id;
        private String name;
        
        public Integer getId() {
            return id;
        }
        
        public void setId(Integer id) {
            this.id = id;
        }
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
    }
  • 相关阅读:
    Linux虚拟机的安装(使用Centos6.3)
    【转载】接口测试用例的设计原则
    Oracle PLSQL游标、游标变量的使用
    利用shell脚本将Oracle服务器中数据定时增量刷新到ftp服务器中
    源码安装rlwrap 0.43(为了方便使用linux下的sqlplus)
    Oracle自定义脱敏函数
    Oracle分析函数FIRST_VALUE、LAST_VALUE
    MYSQL性能测试工具SYSBENCH
    OEL7.6源码安装MYSQL5.7
    OEL7.6安装Oracle Database 19C(VERSION 19.3.0.0)
  • 原文地址:https://www.cnblogs.com/appium/p/12056234.html
Copyright © 2011-2022 走看看