栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot之Controller的使用详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot之Controller的使用详解

本文介绍了 SpringBoot之Controller的使用,分享给大家,具体如下:

1.@Controller:处理http请求

2.@RestController:Spring4之后新加的注解,原来返回json需要@ResponseBody配合@Controller

3.@RequestMapping 配置url映射

1.现在有一个需求(即可以使用localhost:8080/hello和localhost:8080/hi都可以访问):

@RestController
public class HelloController {
  @RequestMapping(value={"/hello","hi"},method = RequestMethod.GET)//使用集合设置
  public String say(){
    return "Hello Spring Boot";
  }
}

SpringBoot获取请求参数

1.@PathVariable–>获取url中的数据

2.@ReqeustParam–>获取请求参数的值,可以设置默认值以及是否必传

3.@GetMapping–>组合注解(相当于@RequestMapping同时限定请求方法为GET 方式)

1.第一种方式:

假如http://localhost:8080/hello为请求,springboot为需要传递的参数:http://localhost:8080/hello/spingboot,获取此种请求的参数的方式,使用@PathVariable注解

@RestController 
public class HelloController {  
  @RequestMapping("/hello/{params}")//获取请求为http://localhost:8080/hello/XXX 类型的参数 
  public String hello(@PathVariable("params") String paramsStr) {//声明一个变量接收请求中的参数 
    return "parameter is "+paramsStr; 
  } 
} 

运行程序,输入http://localhost:8080/hello/spingboot进行测试:

2.第二种方式:

获取请求为http://localhost:8080/hello?params=spingboot类型的参数,使用@RequesParam注解,使用方法为@RequesParam("请求中的参数名params")

@RestController 
public class HelloController { 
  //获取请求为http://localhost:8080/hello?xxx=xxx类型的参数 
  @RequestMapping("/hello") 
  public String hello(@RequestParam("params") String paramsStr) {//requestParam中的参数名称与请求中参数名称要一致  
    return "parameter is "+paramsStr; 
  } 
} 

如:@RequestParam(value="item_id",required=true) String id

@RequestParam中的其他属性:

--required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错

--defaultValue:默认值,表示如果请求中没有同名参数时的默认值

启动程序,输入http://localhost:8080/hello?params=spingboot:

对于@RequestMapping(value="/hello",method = RequestMethod.GET)可以使用:@GetMapping(value="/hello"),如果是Post的话就是用@PostMapping

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号