项目:码神之路
第一步:
springboot常用注解
1.springboot中Controller层的注解
@Controller
作用为处理http请求
@Contoller
public class HelloController{
@RequestMapping(value="/hello",method=RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
如果直接使用@Controller这个注解,当运行该SpringBoot项目后,在浏览器中输入:
localhost:8080/hello,会得到错误:
出现这种情况的原因在于:没有使用模板。即@Controller用来响应页面,@Controller必须配合模板来使用。
pring-boot 支持多种模版引擎包括:
1,FreeMarker
2,Groovy
3,Thymeleaf (Spring 官网使用这个)
4,Velocity
5,JSP (貌似Spring Boot官方不推荐,STS创建的项目会在src/main/resources 下有个templates 目录,这里就是让我们放模版文件的,然后并没有生成诸如 SpringMVC 中的webapp目录)
本文以Thymeleaf为例介绍使用模板,具体步骤如下:
第一步:在pom.xml文件中添加如下模块依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二步:修改控制器代码,具体为:
@Controller
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
第三步:在resources目录的templates目录下添加hello.html文件
其中,hello.html文件中的内容为:
<h1>wojiushimogui</h1>
这样,再次运行此项目后,在浏览器中输入:localhost:8080/hello
就可以
@RestController
Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。
即@RestController是@ResponseBody和@Controller的组合注解。
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
@RequestMapping
@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。
当控制器在类级别上添加RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。
例子一:@RequestMapping仅作用在处理器方法上
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
以上代码sayHello所响应的url=localhost:8080/hello。
例子二:@RequestMapping仅作用在类级别上
/**
* Created by wuranghao on 2017/4/7.
*/
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
以上代码sayHello所响应的url=localhost:8080/hello,效果与例子一一样,没有改变任何功能。
例子三:@RequestMapping作用在类级别和处理器方法上
/**
* Created by wuranghao on 2017/4/7.
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value="/sayHello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
@RequestMapping(value="/sayHi",method= RequestMethod.GET)
public String sayHi(){
return "hi";
}
}
这样,以上代码中的sayHello所响应的url=localhost:8080/hello/sayHello。
sayHi所响应的url=localhost:8080/hello/sayHi。
再讲讲其他注解:
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解
@RequestMapping与@GetMapping和@PostMapping等新注释
@GetMapping注释的使用方法:
@PathVariable注解使用
@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值
@PathVariable("xxx")
通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/hello/show5/1/james