网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SpringBoot中常用注解是什么

这篇文章给大家分享的是有关SpringBoot中常用注解是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

台儿网站建设公司成都创新互联,台儿网站设计制作,有大型网站制作公司丰富经验。已为台儿数千家提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的台儿做网站的公司定做!

SpringBoot 中常用注解

其中,各注解的作用为:

@PathVaribale 获取url中的数据

@RequestParam 获取请求参数的值

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

@RestController是@ResponseBody和@Controller的组合注解。

@PathVaribale 获取url中的数据

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

@RestController
public class HelloController {

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

SpringBoot中常用注解是什么

@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,可以看到如下的结果:

SpringBoot中常用注解是什么

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

@GetMapping 组合注解

@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。

即可以使用@GetMapping(value = “/hello”)来代替@RequestMapping(value=”/hello”,method= RequestMethod.GET)。即可以让我们精简代码。

例子

@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的组合注解。

@RestController
public class HelloController {

  @RequestMapping(value="/hello",method= RequestMethod.GET)
  public String sayHello(){
    return "hello";
  }
}

与下面的代码作用一样

@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中常用注解是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


分享标题:SpringBoot中常用注解是什么
文章分享:http://bjjierui.cn/article/gpijis.html

其他资讯