SpringWebMVC常用注解
@RequestMapping
@RequestMapping注解的作用是将Web请求与控制器类中的方法进行映射,在使用@RequestMapping的同时,需要对控制器使用@Controller或@RestController进行标记,关于@Controller和@RestController会在后边讲解。
@RestController
class RequestMappingController {
@RequestMapping("/requestMapping",method = [RequestMethod.POST])
fun requestMapping():String{
return "hello"
}
}
@RequestMapping也可以作用到控制器类中,这样做的好处就是可以将请求路径中的公共部分统一抽取出来,方便管理。同时控制器中的不同方法只需要配置每个方法特有的路径就行了,系统会自动将类RequestMapping中的路径与方法上RequestMapping的路径拼接形成一个完整的路径。
@RestController
@RequestMapping("/requestMapping",method = [RequestMethod.POST])
class RequestMappingController {
@RequestMapping
fun requestMapping():String{
return "hello"
}
}
@RequestBody
@RequestBody注解主要用来接收前端或者App传递过来的请求体中的数据,可以和@RequestParam同时使用,可以单独使用。看一下如何使用使用postman发送请求ReqeustBody请求。
首先创建一个接收参数用的bean类。
data class RequestBody(val name:String,val age:Int)
然后创建一个控制器,用来处理发送过来的请求。
@RequestMapping("/requestBody",method = [RequestMethod.POST])
@RestController
class RequestBodyController{
@PostMapping("/body")
fun requestBody(@RequestBody body: com.henk.annotations.RequestBody):String{
return body.name
}
}
使用PostMan发送请求。@RequestBody注解的方法在发送请求时候需要在body中填写请求体对应的JSON串,并且请求的报文格式要指定为JSON格式,系统会自动尝试将JSON串中的内容进行对应。
@RequestParam
同@RequestBody一样,也是用来接收前端发送过来的数据的,不同的是@RequestBody注解的方法中是需要有一个实体对象作为参数的,@RequestParam注解的方法其参数类型除了实体类还可以是普通元素,列表,数组等。不同的参数类型就导致发送请求的过程也是不同的,RequestBody要求的请求体是一段JSON报文,发送和接收报文的过程中系统会自动将JSON中的字段与参数对象中的字段对应。而RequestParam则要求请求体中的内容是kay-value键值对的形式,并且参数个数、名字、类型等都要与注解方法中要求的一致。
@RequestMapping("/requestBody",method = [RequestMethod.POST])
@RestController
class RequestParamController{
@PostMapping("/param")
fun requestBody(@RequestParam name:String,@RequestParam age:Int):String{
return name
}
}
@GetMapping
@GetMapping主要用来处理GET请求,并且将请求映射到对应的方法上。@GetMapping其实相当于@RequestMapping(method=RequestMethod.GET)的简化写法。
一个@GetMapping示例:
@RequestMapping("/getMapping")
@RestController
class GETController{
@GetMapping("/get")
fun requestBody(@RequestParam name:String,@RequestParam age:Int):String{
return name
}
}
PostMan运行结果:
@PostMapping
与@GetMapping类似,@PostMapping主要用于处理POST请求,并且将请求映射到对应的方法上,是@RequestMapping(method=RequestMethod.POST)的简化写法。
一个@PostMapping示例:
@RequestMapping("/postMapping")
@RestController
class POSTController{
@PostMapping("/post")
fun requestBody(@RequestParam name:String,@RequestParam age:Int):String{
return name
}
}
这一小节先介绍几个注解,还有一些常用的注解会在以后的小节中介绍。