Spring MVC---@RequestMapping,@GetMapping等注解

 

参考 Spring MVC @RequestMapping注解详解

@RequestMapping 注解作用:

  • 用在类上, 表示这个类是一个控制器类,value 相当于一个命名空间,即访问该 Controller 下的任意方法都需要带上这个命名空间
  • 或者类的方法上,value值 声明这个方法所要处理的请求URL 地址

@RequetMapping参数:

  • value: 注解的方法 能处理的 请求url。 值是一个String,或者一个String 类型的数组。
  • method: 注解的方法 能处理的 请求方式 :GET或者POST

Spring MVC中,控制器的定义

在Spring MVC中,控制器 是指 类或者类的方法上 添加了@RequestMapping注解的类,并不是 使用了 @Controller注解的类 就是 控制器类。

@Controller 注解的类 和@Component注解的类 在功能上是一样的,都是在 辅助@ComponentScan 实现组件扫描。

只是在表意上,在用@Controller 注解控制器类比用@Component 注解控制器类 更清楚一些

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

参考 PUT 还是 POST ? 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping("/create")
    public void create(@RequestBody PersonRequest request) {
        personService.create(request);
    }

    @PutMapping("/edit")
    public void edit(@RequestBody PersonRequest request) {
        personService.edit(request);
    }

    @PutMapping("/list")
    public ResponseEntity<?> findAll(@RequestBody PersonRequest request) {
        List<PersonResponse> responses = personService.findAll(request);
        return ResponseEntity.ok(responses);
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> findOne(@PathVariable String id) {
        PersonResponse response = personService.findOne(id);
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable String id) {
        personService.delete(id);
    }
}

 

posted on 2021-01-15 15:00  dreamstar  阅读(391)  评论(0编辑  收藏  举报