服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot 中常用注解及各种注解作用

SpringBoot 中常用注解及各种注解作用

2021-04-09 11:16程序员的那些事 Java教程

本篇文章将介绍几种SpringBoot 中常用注解及各个注解的作用,感兴趣的朋友跟随脚本之家小编一起学习吧

本篇文章将介绍几种springboot 中常用注解

其中,各注解的作用为:

@pathvaribale 获取url中的数据

@requestparam 获取请求参数的值

@getmapping 组合注解,是@requestmapping(method = requestmethod.get)的缩写

@restcontroller是@responsebody和@controller的组合注解。

@pathvaribale 获取url中的数据

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

?
1
2
3
4
5
6
7
8
@restcontroller
public class hellocontroller {
 
  @requestmapping(value="/hello/{id}",method= requestmethod.get)
  public string sayhello(@pathvariable("id") integer id){
    return "id:"+id;
  }
}

SpringBoot 中常用注解及各种注解作用

@requestparam 获取请求参数的值

直接看一个例子,如下

?
1
2
3
4
5
6
7
8
@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,可以看到如下的结果:

SpringBoot 中常用注解及各种注解作用

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

@getmapping 组合注解

@getmapping是一个组合注解,是@requestmapping(method = requestmethod.get)的缩写。该注解将http get 映射到 特定的处理方法上。

即可以使用@getmapping(value = “/hello”)来代替@requestmapping(value=”/hello”,method= requestmethod.get)。即可以让我们精简代码。

例子

?
1
2
3
4
5
6
7
8
9
@restcontroller
public class hellocontroller {
  //@requestmapping(value="/hello",method= requestmethod.get)
  @getmapping(value = "/hello")
  //required=false 表示url中可以不穿入id参数,此时就使用默认参数
  public string sayhello(@requestparam(value="id",required = false,defaultvalue = "1") integer id){
    return "id:"+id;
  }
}

@restcontroller

spring4之后新加入的注解,原来返回json需要@responsebody@controller配合。

@restcontroller@responsebody@controller的组合注解。

?
1
2
3
4
5
6
7
8
@restcontroller
public class hellocontroller {
 
  @requestmapping(value="/hello",method= requestmethod.get)
  public string sayhello(){
    return "hello";
  }
}

与下面的代码作用一样

?
1
2
3
4
5
6
7
8
9
@controller
@responsebody
public class hellocontroller {
 
  @requestmapping(value="/hello",method= requestmethod.get)
  public string sayhello(){
    return "hello";
  }
}

注解@requestparam 和 @pathvarible的区别

@requestparam是请求中的参数。如get?id=1

@pathvarible是请求路径中的变量如 get/id=1

总结

以上所述是小编给大家介绍的springboot 中常用注解及各种注解作用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/xubb/p/8492259.html

延伸 · 阅读

精彩推荐