SpringBoot入门(二):Controller的使用
Controller中注解的使用:
@Controller
●该注解用来响应页面,必须配合模板来使用
@RestController
●该注解可以直接响应字符串,返回的类型为JSON格式
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RestController; 5 6 @RestController 7 public class HelloWorldController { 8 9 @RequestMapping("/") 10 public String index() { 11 return "Hello World"; 12 } 13 }
启动程序,访问http://localhost:8080/,返回Hello World
@RequestMapping
●指定URL访问中的前缀
1 package com.example.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 @SpringBootApplication 7 public class DemoApplication { 8 9 public static void main(String[] args) { 10 SpringApplication.run(DemoApplication.class, args); 11 } 12 }
访问http://localhost:8080/hello,返回Hello World
@RequestParam
●获取请求URL中参数的变量
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RequestMethod; 5 import org.springframework.web.bind.annotation.RequestParam; 6 import org.springframework.web.bind.annotation.RestController; 7 8 @RestController 9 public class HelloWorldController { 10 11 @RequestMapping(value="/hello",method=RequestMethod.GET) 12 public String index(@RequestParam("name")String name) { 13 return "Hello World:"+name; 14 } 15 }
访问http://localhost:8080/hello?name=张三,返回Hello World:张三
@PathVariable
●获取请求URL中路径的变量
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.PathVariable; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 import org.springframework.web.bind.annotation.RestController; 7 8 @RestController 9 public class HelloWorldController { 10 11 @RequestMapping(value="/hello/{name}",method=RequestMethod.GET) 12 public String index(@PathVariable("name")String name) { 13 return "Hello World:"+name; 14 } 15 }
访问http://localhost:8080/hello/张三,返回Hello World:张三
@GetMapping/@PostMapping
●与RequestMapping类似,不同的是指定了请求的方式(get/post)
1 package com.example.demo.controller; 2 3 import org.springframework.web.bind.annotation.GetMapping; 4 import org.springframework.web.bind.annotation.RestController; 5 6 @RestController 7 public class HelloWorldController { 8 9 @GetMapping(value="/hello") 10 public String index() { 11 return "Hello World"; 12 } 13 }
总结
Controller是SpringBoot里比较常用的组件,通过匹配客户端提交的请求,分配不同的处理方法,然后向客户端返回结果。