美文网首页
Spring常用注解

Spring常用注解

作者: Leon_001 | 来源:发表于2020-05-19 01:03 被阅读0次
  1. 处理URL中的参数的注解@ PathVaribale / @ RequestParam

其中,各注解的作用为:

@PathVaribale获取url中的数据

url只有一个参数时:localhost/hello/11


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

url有多个参数时:hocalhost/hello/12/lee

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

@RequestParam获取请求参数的值

url只有一个参数时:localhost/hello?id=11

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

id使用默认值

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

url有多个参数时:hocalhost/hello?id=11&name=lee

/**
 * Created by wuranghao on 2017/4/7.
 */
@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){
        return "id:"+id+ " name:"+name;
    }
}

相关文章

网友评论

      本文标题:Spring常用注解

      本文链接:https://www.haomeiwen.com/subject/ucomohtx.html