【SpringBoot】Controller

常用注解

@Controller

表明该类是SpringMVC里的Controller
1. Dispatcher Servlet会自动扫描该类; 2. Web请求映射到注解了@RequestMapping的方法上;

@RequestMapping

用来映射Web请求、处理类和方法
可注解在类和方法上,注解在方法上的路径会继承注解在类上的路径

@ResponseBody

支持返回值放在response体内,而不是一个页面
该注解放在返回值前或方法上

@RequestBody

允许request的参数在request体中,而不是在地址后面
该注解放在参数前

@PathVariable

用来接收路径参数,如/user/01
该注解放在参数前

@RestController

组合注解,组合了@Controller和@ResponseBody
用于开发和页面交互数据的控制

基本使用

@Controller + 模板

1.添加pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.添加html页面

这里写图片描述

3.修改Controller

这里写图片描述

4.效果如下

这里写图片描述


@RestController方法

  1. 修改Controller

这里写图片描述

使用 http://localhost:8080/myboot/morning/hellohttp://localhost:8080/myboot/morning/hi 都可以得到如下效果

这里写图片描述
这里写图片描述


参数使用

访问:localhost:8080/hello/123

@RequestMapping(value="hello",method=RequestMethod.GET)
public String hello(@PathVariable("id") Integer id){
    return "id:" + id;
}

访问:localhost:8080/hello?id=123

@RequestMapping(value="hello",method=RequestMethod.GET)
public String hello(@RequestParam(value="id",required=false,defaultValue="0") Integer id){
    return "id:" + id;
}

小结

一般项目采取前后端分离的形式,所以常常使用@RestController的形式
如果使用模板,也会带来性能的损耗

猜你喜欢

转载自blog.csdn.net/Francis123580/article/details/81434395