spring boot Controller 学习笔记一

场景:访问 localhost:8080/controller/hello,显示Hello world
通过最简单的场景,让我们对spring boot 有个大概的印象。包括如何搭建一个spring boot 基本环境,及使用@RestController搭配@RequestMapping来获取请求信息。

搭建spring boot 工作环境

  • 加载maven依赖(应该也支持gradle)
  • 创建spring application 注意最好放到最外层目录,默认自动搜索启动程序之下的所有类
//入口类
@SpringBootAppliction
public class HelloApplication
{
  public static void main(String[] args)
  {
    SpringApplication.run(HelloApplication.class, args); //run(Object source, String... args)
  }
}

创建控制器

  • 在/controller目录下创建HelloController类
@Controller
@RequestMapping("/controller")
public class HelloController
{
  @RequestMapping("/hello")
  public @ResponseBody String sayHello() //默认返回是视图名称,@ResponseBody可以返回json格式字符串
  {
    return "hello world";
  }
}

Restful 风格 效果同上

@RestController //相当于@Controller + @ResponseBody
@RequestMapping("/controller")
public class HelloController
{
  @RequestMapping("/hello")
  public String sayHello()
  {
    return "hello world";
  }
}

Http几种常用的请求方式在@RestController中的表现形式
@GetMapping("/hello") ==> @RequestMapping(value="/hello", method = RequestMethod.GET)
@PostMapping("/hello")
@PutMapping("/hello")
@DeleteMapping("/hello")

你可能感兴趣的:(spring boot Controller 学习笔记一)