本文介绍了SpringBoot之控制器的使用,分享给大家,具体如下:
1。@ controller:处理http请求
2。@RestController: Spring4之后新加的注解,原来返回json需要@ResponseBody配合@ controller
3。@RequestMapping配置url映射
<强> 1。现在有一个需求(即可以使用localhost: 8080/hello和localhost: 8080/嗨都可以访问):强>
@RestController 公开课HelloController { @RequestMapping (value=https://www.yisu.com/zixun/{“/hello”,“嗨”},方法=RequestMethod.GET)//使用集合设置 公共字符串表示(){ 返回“你好弹簧引导”; } }
<强> SpringBoot获取请求参数强>
1 .@PathVariable→获取url中的数据
2 .@ReqeustParam→获取请求参数的值,可以设置默认值以及是否必传
3 .@GetMapping→组合注解(相当于@RequestMapping同时限定请求方法为得到方式)
<强> 1。第一种方式:强>
假如http://localhost: 8080/你好为请求,springboot为需要传递的参数:http://localhost: 8080/hello/spingboot获取此种请求的参数的方式,使用@PathVariable注解
@RestController 公开课HelloController { @RequestMapping ("/hello/{params} ")//获取请求为http://localhost: 8080/hello/XXX类型的参数 公共字符串你好(@PathVariable (params)字符串paramsStr){//声明一个变量接收请求中的参数 返回“参数”+ paramsStr; } }
运行程序,输入http://localhost: 8080/hello/spingboot进行测试:
<强> 2。第二种方式:强>
获取请求为http://localhost: 8080/你好# 63;params=spingboot类型的参数,使用@RequesParam注解,使用方法为@RequesParam(“请求中的参数名参数”)
@RestController 公开课HelloController {//获取请求为http://localhost: 8080/喂? xxx=xxx类型的参数 @RequestMapping (“/hello”) 公共字符串你好(@RequestParam (params)字符串paramsStr) {//requestParam中的参数名称与请求中参数名称要一致 返回“参数”+ paramsStr; } } >之前如:@RequestParam (value=" https://www.yisu.com/zixun/item_id ",要求=true)字符串id
@RequestParam中的其他属性:
——要求:是否必须,默认是真的,表示请求中一定要有相应的参数,否则将报错
——defaultValue:默认值,表示如果请求中没有同名参数时的默认值
启动程序,输入http://localhost: 8080/你好# 63;params=spingboot:
对于@RequestMapping (value=" https://www.yisu.com/hello ",方法=RequestMethod.GET)可以使用:@GetMapping (value=" https://www.yisu.com/hello "),如果是帖子的话就是用@PostMapping
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
SpringBoot之控制器的使用详解