这里有新鲜出炉的精品教程, 程序狗速度看过来!
Spring Boot
Spring Boot 项目旨在简化创建产品级的 Spring 应用和服务你可通过它来选择不同的 Spring 平台可创建独立的 Java 应用和 web 应用, 同时提供了命令行工具来允许'spring scripts'.
本篇文章主要介绍了 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
来源: http://www.phperz.com/article/18/0320/355035.html