controller 及 url 映射
- @Controller 处理 http 请求
- @RestController,Spring4 之后新加的注释,返回原来的json 需要 @ResponseBody 配合 @Controller
- @RequestMapping 配置 url 映射
1. @Controller 和模板一起使用
@Controller 这个注解需要和模板一起使用。
- 修改 IndexController 文件
@Controller
public class IndexController{
@Autowired
private myProperties prop;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String say(){
return prop.getBook();
}
}
- pom.xml 中增加模板相关的插件。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 在 templates 中添加 index.html 文件
注意:生成的 meta 不是闭合标签,需要改为 <meta /> - 修改 IndexController 中相关的代码
@Controller
public class IndexController{
@Autowired
private myProperties prop;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String say(){
return "index";
}
}
2. @RestController = @Controller + @ResponseBody
@RestController = @Controller + @ResponseBody
@Controller
@ResponseBody
public class IndexController{
@AutoWired
private myProperties prop;
@RequestMapping(value="/", method = RequestMethod.GET)
public String say(){
return prop.getBook();
}
}
3. RequestMapping ,从 url 到 方法的映射
- 多网址指向同一个方法
@RequestMapping(value = {"/","/hello"}, method=RequestMethod.GET)
public String say(){
return prop.getBook();
}
- 给整个类注解路径
@RestController
@RequestMapping(value="/root", method= RequestMethod.GET)
public class IndexController{
@AutoWired
private myProperties prop;
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String say(){
return prop.getBook();
}
}
这样,两个地址拼接起来才能访问到,如 “http://localhost:8080/root/hi”
- 支持正则表达式 / 变量名
url 中的参数
- @PathVariable, 获取 url 中变量的值
- @RequestParam, 获取请求参数的值
- @GetMApping, 组合注解
1. @PathVariable 获取 url 中变量的值
修改 IndexController
@RestController
@RequestMapping(value = "/root/{id}", method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id){
return "ID: " + id
}
测试网址,http://localhost:8080/root/233
2. @RequestParam 获取url中传递的值
- @RequestParam 获取 url 中传递值,
@RestController
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say(RequestParam("local") String local
RequestParam("local") String time){
return local + " : " + time;
}
}
测试地址:http://localhost:8080/hello?local=Hangzhou&time=2018
- @RequestParam 获取 url 中传递值,设置默认值及是否必须传值
@RestController
public class IndexController(){
@RequestMapping("/hello", method = RequestMethod.GET)
public say(@RequestParam(value="local", Required = false, defaultValue = "hangzhou" String local)){
return local;
}
}
3. @GetMapping, @RequestMapping 的简化写法
@RestController
public class IndexController(){
@GetMapping("/hello")
public say(@RequestParam(value = "local", required = false, defaultValue = "hangzhou" String local)){
return local;
}
}
同理还有,PostMapping / DeleteMapping