1.Controller的使用
常用注解
1.1.@Controller
需要配合模版使用
在pom.xml中加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在resource下面创建templates文件夹,创建index.html
直接在controller中写如下格式:
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
return "index";
}
}
即可跳转到index页面
对于目前前后端分离的开发趋势,不建议采用thymeleaf的依赖形势,会影响性能。
1.2.@RestController
@RestController = @Controller+@ResponseBody
@Controller
@ResponseBody
public class HelloController {
@Autowired
private DbConfig dbConfig;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
return "Hello Spring Boot" + dbConfig.getUrl();
}
}
为了简洁常采用@RestController
1.3.@RequestMapping
对于多映射多访问url,采用如下格式
@RequestMapping(value = {"/hello","/hi"}, method = RequestMethod.GET)
也可以在类上面写@RequestMapping
格式如下:
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@Autowired
private DbConfig dbConfig;
@RequestMapping(value = "/say", method = RequestMethod.GET)
public String say() {
return "Hello Spring Boot" + dbConfig.getUrl();
}
}
Url中参数的注解
1.4.@PathVariable
获取url中的数据
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@RequestMapping(value = "/say/{id}", method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id) {
return "id" + id;
}
}
访问地址:
http://localhost:8081/molly/hello/say/34
1.5.@RequestParam
获取请求参数的值
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@RequestMapping(value = "/say", method = RequestMethod.GET)
public String say(@RequestParam("id") Integer myid) {
return "id:" + myid;
}
}
访问地址:
http://localhost:8081/molly/hello/say?id=39
id也可以不传入,格式如下
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@RequestMapping(value = "/say", method = RequestMethod.GET)
public String say(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id) {
return "id:" + id;
}
}
required必填标志,defaultValue默认值
1.6.@GetMapping
组合注解
简化mapping注解
@RequestMapping(value = "/say", method = RequestMethod.GET)等同于
@GetMapping(value = "/say")
同理还有@PostMapping(value = "/say")