SpringBoot(三)_controller的使用
2018-05-27 20:56
381 查看
针对controller 中 如何使用注解进行解析
@RestController
返回数据类型为 Json 字符串,特别适合我们给其他系统提供接口时使用。@RequestMapping
(1) 不同前缀访问同一个方法,此时访问hello和hi 都可以访问到say()这个方法@RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET) public String say(){ return girlProperties.getName(); }
(2)给类一个RequestMapping, 访问时就是:http://localhost:8099/hello/say
@RestController @RequestMapping("/hello") public class HelloController { @Resource private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(){ return girlProperties.getName(); } }
@PathVariable:获取url中的数据
@RestController @RequestMapping("/hello") public class HelloController { @Resource private GirlProperties girlProperties; @RequestMapping(value = "/say/{id}",method = RequestMethod.GET) public String say(@PathVariable("id") Integer id){ return "id :"+id; } }
访问http://localhost:8099/hello/say/100, 结果如下
id :100
@RequestParam :获取请求参数的值
(1) 正常请求@RestController @RequestMapping("/hello") public class HelloController { @Resource private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(@RequestParam("id") Integer id){ return "id :"+id; } }
访问 http://localhost:8099/hello/say?id=111 结果如下
id :111
(2)设置参数非必须的,并且设置上默认值
@RestController @RequestMapping("/hello") public class HelloController { @Resource private GirlProperties girlProperties; @RequestMapping(value = "/say",method = RequestMethod.GET) public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id){ return "id :"+id; } }
访问http://localhost:8099/hello/say 结果如下
id :0
@GetMapping ,当然也有对应的Post等请求的简化写法
这里对应的就是下面这句代码@GetMapping("/say") //等同于下面代码 @RequestMapping(value = "/say",method = RequestMethod.GET)
相关文章推荐
- Spring Boot 学习——Controller的使用
- springboot-controller的使用详解
- spring-mvc springboot 使用MockMvc对controller进行测试
- SpringBoot中Controller以及Jpa操作数据库的使用
- springBoot Controller的使用
- springboot快速入门(三)——Controller的使用
- SpringBoot入门(三)Controller的使用
- SpringBoot的Controller使用
- Spring Boot项目@RestController使用重定向redirect
- SpringBoot 使用MockMvc进行Controller的测试
- springBoot使用Controller读取配置文件两种方式&读取自定义配置方法
- Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验 使用消息资源文件对消息国际化
- SpringBoot之Controller的使用详解
- SpringBoot的Controller使用
- 关于怎么解决从ajax传入的json参数注入到Controller的接收对象 以及如何在Spring Boot项目使用参数校验
- SpringBoot第2小节:Controller(控制器)的使用
- 六、Spring Boot Controller使用
- SpringBoot-Controller的使用
- spring boot中controller的使用及url参数的获取方法
- springboot使用addViewController减少控制器代码的编写