注解一:@Controller作用于类,处理http请求

作用一:controller、view,使用Controller来相应页面 。

spring-boot 支持多种模版引擎包括: 

1. FreeMarker 
2. Groovy 
3. Thymeleaf (Spring 官网使用这个) 

4. Velocity    

1.) 本文使用第三个Thymeleaf为例,在pom.xml中配置

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

2.)新建HelloController类,如下

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController


    在浏览器输入localhost:8080/home/hey会出现如下的错误,那是因为没有对应的模板页面

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController


解决:在src/teplates/下新建hello.html文件,并编辑

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

接着在访问浏览器,成功!

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController


作用二:@Controller、@ResponseBody组合返回json数据

当要返回json数据时,使用@ResponseBody注解

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

路由访问localhost:8080/home/hello   如下图所示:

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

注解二:@RequestMapping,配置url映射,该注解可以应用于控制器上,也可以单独应用到控制器内部的处理方法上

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

当作用于HelloController时,会对类内的所有方法响应

如访问: localhost:8080/home/hello

              localhost:8080/home/hi

例如移除1中的@RequestMapping注解,

              localhost:8080/hi

              localhost:8080/hello

注解三:@RestController注解,Spring4之后新加入的注解,是@Controller和@ResponseBody的组合注解

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

同样返回如下内容

SpringBoot入门(一):注解 @Controller @RequestMapping以及@RestController

相关文章:

  • 2021-06-14
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
猜你喜欢
  • 2022-01-01
  • 2021-09-07
  • 2021-11-26
  • 2022-03-07
  • 2022-02-19
  • 2021-11-21
相关资源
相似解决方案