美文网首页
SpringBoot学习(三)

SpringBoot学习(三)

作者: 零下的雨 | 来源:发表于2018-11-08 09:49 被阅读0次

七、Controller使用

@RestController 等同于@Controller+@ResponseBody的组合,放在类的前面,表示这是个控制器bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。

     @Controller:用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping

      @ResponseBody:表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@esponsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@Responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用。

@RequestMapping 提供路由信息,负责指定url到不同controller中具体函数的映射。

        可以指定多个url,把多个url写到一个集合里,比如

        @RequestMapping(value={"/hello","/hi"},method = RequestMethod.GET)

        @RequestMapping也可以写到类前面,@RequestMapping(value="/hello"),访问url时要加上这个参数值。

处理url中的参数,查看如下代码:

//使用@PathVariable("id") Integer id ,从浏览器输入时获取参数值,Integer id是自定义的参数,

@RequestMapping(value ="/hello/{idnum}",method =RequestMethod.GET)

public Stringsaytwo(@PathVariable("idnum") Integer id){

return "输入的id是:"+id;

}

//可以把参数值写到url的中间

@RequestMapping(value ="/{idnum}/hello",method =RequestMethod.GET)

public Stringsaythree(@PathVariable("idnum") Integer id){

return "输入的id是:"+id;

}

//使用@RequestParam("id"),在url后面以问号的方式携带参数,比如/hellosayfour/id=666,获取666的值并返回到浏览器中

@RequestMapping(value ="/hellosayfour",method =RequestMethod.GET)

public Stringsayfour(@RequestParam("id") Integer myid){

return "id:"+myid;

}

//@RequestParam(value="id",required = false,defaultValue = "5")是指没有输入值时取默认的值,默认值为5

@RequestMapping(value ="/hellosayfive",method =RequestMethod.GET)

public Stringsayfive(@RequestParam(value="id",required =false,defaultValue ="5") Integer myid){

return "id:"+myid;

}

//@RequestMapping注解可以用@GetMapping(value = "/hellosaysix")代替,post注解可以用@PostMapping

@GetMapping(value ="/hellosaysix")

public Stringsaysix(@RequestParam(value="id",required =false,defaultValue ="6") Integer myid){

return "id:"+myid;

}

相关文章

网友评论

      本文标题:SpringBoot学习(三)

      本文链接:https://www.haomeiwen.com/subject/psumxqtx.html