请求

  1. @RequestParam ```java package com.itheima.mvctest.controller;

import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;

/**

  • @author liqp
  • @version 1.0
  • @date 2021/11/22 / @RestController @RequestMapping(“user”) public class UserController { /*

  1. 2. @PathVarible
  2. ```java
  3. /**
  4. * PathVariable 路径变量 http://localhost:8080/user/get3/2
  5. * @param id
  6. */
  7. @GetMapping("get3/{id}")
  8. public void get3(@PathVariable("id") Integer id){
  9. System.out.println(id);
  10. }
  1. @ReuqestBody
    /**
      * localhost:8080/user/get4
      * body:
      * {
      *     "id":1,
      *     "userName":"zhangsan",
      *     "password":"123"
      * }
      * @param user
      */
     @GetMapping("get4")
     public void get4(@RequestBody User user){
         System.out.println(user);
     }
    
    image.png

响应

  1. 响应json字符串 ```java /*
    • @return 返回json字符串 */ @GetMapping(“get5”) public User get5() { User user = new User(); user.setId(1); user.setUserName(“zhangsan”); user.setPassword(“123”); return user; }

2. _ResponseEntity 响应200_
```java
/**
     *
     * @return ResponseEntity 指定响应体
     */
    @GetMapping("get6")
    public ResponseEntity<User> get6() {
        User user = new User();
        user.setId(1);
        user.setUserName("zhangsan");
        user.setPassword("123");
        return ResponseEntity.ok(user);
    }
  1. ResponseEntity 自定义状态码 ```java /**

    • 自定义状态码
    • @return */ @GetMapping(“get7”) public ResponseEntity get7() { User user = new User(); user.setId(1); user.setUserName(“zhangsan”); user.setPassword(“123”); //返回404 //return ResponseEntity.status(HttpStatus.NOT_FOUND).body(user);

      //返回500 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(user); }


4. _ResponseEntity 定义响应头_
```java
/**
     *   自定义响应头
     * @return
     */
    @GetMapping("get8")
    public ResponseEntity<User> get8() {
        User user = new User();
        user.setId(1);
        user.setUserName("zhangsan");
        user.setPassword("123");
        //return ResponseEntity.ok().header("itcats", "itheima").body(user);
        //指定状态码为500 ,设置响应头:itcats:itheima, 设置响应体:user
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).header("itcats", "itheima").body(user);
    }