0%

SpringBoot——Controller

Controller中相关的注解

  • @Controller:表示一个类为Controller,return时会被视图处理器识别成静态文件的路径。默认为templates文件夹下。如return "test/hello"表示的是默认路径下的test文件夹中的名叫hello的文件,带上后缀名.html或btl等也可以识别。

  • @ResponseBody:可以标注方法也可以标注类,当标注方法时表示该方法的返回值会被解析成json(字符串会不会被转换),直接写入HTTP Response Body中,视图处理器将不会将return的参数识别成路径。当它标注类时,类中所有方法的返回值都将直接返回值到页面,相当于给所有的方法都加上@ResponseBody注解。

  • @RestController:@RestController是@Controller和@ResponseBody的结合体,只能注解类,return返回的值将被转换成json,字符串除外,直接写入HTTP相应体返回到页面中。

  • @RequestMapping:它可以注解类也可以注解方法,注解类时标注请求的路径,标注方法时表示将特定的URL映射到指定的方法。@RequestMapping中有多个属性来进一步匹配HTTP请求到方法,例如下面代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Controller
    @RequestMapping("/coffee")
    @Slf4j
    public class CoffeeController {
    @Autowired
    private CoffeeService coffeeService;
    //GetMapping是RequestMapping+Get请求的结合体
    @GetMapping(path="/", params = "!name")
    @ResponseBody
    public List<Coffee> getAll(){
    return coffeeService.getAllCoffee();
    }
    }
    • RequestMapping的一些参数:
      1. value:指定请求的实际地址,指定的地址可以是URI Template 模式;
      2. path:和value一样
      3. method:指定请求的method类型, GET、POST、PUT、DELETE等
      4. params:指定request中必须包含某些参数值时,才让该方法处理。
      5. headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
      6. consumes:指定处理请求的提交内容类型(Content-Type)
      7. produces:指定返回的内容类型(Accept)
  • @PathVariable:用于获取URL中的参数:一般{ }中的变量名与方法中的形参名一致(可以不加@PathVariable注解),如下面代码:

    1
    2
    3
    4
    5
    6
    7
    8
    @GetMapping(path = "/{id}")
    @ResponseBody
    public ResponseEntity<Coffee> getById(@PathVariable Long id){
    Coffee coffee = coffeeService.getCoffee(id);
    return ResponseEntity.ok()
    .cacheControl(CacheControl.maxAge(10, TimeUnit.SECONDS))
    .body(coffee);
    }
  • @RquestParam:用来获取URL中查询参数的值:params中的变量名与方法中的形参名一致,如下面代码:

    1
    2
    3
    4
    5
    @GetMapping(params = {"name"})
    @ResponseBody
    public Coffee getByName(@RequestParam String name){
    return coffeeService.getCoffee(name);
    }
  • @ResponseStatus:用于设置返回响应的状态码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @PostMapping(path = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    //返回201CREATED状态码
    @ResponseStatus(HttpStatus.CREATED)
    public Coffee addCoffee(@Valid NewCoffeeRequest newCoffee, BindingResult result){
    if (result.hasErrors()){
    log.warn("errors:{}", result);
    throw new FormValidationException(result);
    }
    return coffeeService.saveCoffee(newCoffee.getName(), newCoffee.getPrice());
    }
  • @Get/Post/Put/DeleteMapping:主要用来匹配RestfulApi的请求,其实就是RequestMapping+一些请求Method

处理响应的两种方式

  • 使用默认返回的方式
1
2
3
4
5
6
7
8
9
10
@PostMapping(path = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public Coffee addCoffee(@Valid NewCoffeeRequest newCoffee, BindingResult result){
if (result.hasErrors()){
log.warn("errors:{}", result);
throw new FormValidationException(result);
}
return coffeeService.saveCoffee(newCoffee.getName(), newCoffee.getPrice());
}
  • 使用ResponseEntity

    使用ResponseEntity有两种写法:

    1. 构造ResponseEntity,可以在构造器中传入响应体body、响应头headers、状态码status
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Coffee> addJsonCoffee(@RequestBody @Valid NewCoffeeRequest newCoffee, BindingResult result){
    if (result.hasErrors()){
    log.warn("errors:{}", result);
    throw new ValidationException(result.toString());
    }
    Coffee coffee = coffeeService.saveCoffee(newCoffee.getName(), newCoffee.getPrice());
    //设置响应头参数
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("MyResponseHeader", "MyValue");
    return new ResponseEntity<>(coffee, responseHeaders, HttpStatus.CREATED);
    }
    1. 采用链式调用,这里可以使用HeaderBuilder和BodyBuilder设置一些关于Header和Body的一些熟悉,例如:缓存相关的cacheControl、ETag、LastModify等、响应体相关的ContentType、ContentLength、路由相关的Location、Allow等。
    1
    2
    3
    4
    5
    6
    7
    8
    @GetMapping(path = "/{id}")
    @ResponseBody
    public ResponseEntity<Coffee> getById(@PathVariable Long id){
    Coffee coffee = coffeeService.getCoffee(id);
    return ResponseEntity.ok()
    .cacheControl(CacheControl.maxAge(10, TimeUnit.SECONDS))
    .body(coffee);
    }
-------------本文结束感谢您的阅读-------------