Spring Boot学习(一)之Controller的使用

来源:互联网 发布:网络乾坤 编辑:程序博客网 时间:2024/06/08 04:34

@Controller:处理http请求

@RestController:

@RestController注解相当于@ResponseBody + @Controller合在一起的作用。Spring4之后新加入的注解,原来返回json需要@ResponseBody配合@Controller


@RequestMapping:配置url映射,可用于用户通过某个url访问到我们写的方法


例子:

@RestController@RequestMapping("/hello")public class HelloController {   @Autowired   private GirlProperties girlProperties;    @RequestMapping(value = "/say",method = RequestMethod.POST)    public String say(){        return girlProperties.getCupSize();    }}
这时访问地址就是:127.0.0.1:8080/hello/say



@PathVariable:获取url中的数据

@RequestMapping(value = "/say/{id}",method = RequestMethod.GET)public String say(@PathVariable("id") Integer id){    return "id"+id;   // return girlProperties.getCupSize();}

仔细看url,后面的参数比起传统的更加简洁,传统get方法获取参数如下面所示


@RequestParam:获取请求参数的值

@RestController@RequestMapping("/hello")public class HelloController {   @Autowired   private GirlProperties girlProperties;    @RequestMapping(value = "/say",method = RequestMethod.GET)    public String say(@RequestParam("id") Integer myid){        return "id"+myid;    }}


public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id){    return "id"+id;}
其中,required:表示是否一定要设置参数id的值,false表示不需要;defaultValue:表示默认值为0(注意要用“”引着)


@GetMapping:组合注解

//@RequestMapping(value = "/say",method = RequestMethod.GET)@GetMapping(value = "/say")
这两句代码作用是一样的,但是组合注解减少了代码量。除了@GetMapping这个组合注解,还有其它的如PostMapping等组合注解!!


原创粉丝点击