请求
- @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 { /*
- http://localhost:8080/user/get1?userName=zhangsan
@param userName */ @GetMapping(“get1”) public void get1(String userName){ System.out.println(userName); }
/**
- @RequestParam 请求参数 http://localhost:8080/user/get2?userName=zhangsan
- @param userName2 */ @GetMapping(“get2”) public void get2(@RequestParam(“userName”) String userName2){ System.out.println(userName2); } }
2. @PathVarible
```java
/**
* PathVariable 路径变量 http://localhost:8080/user/get3/2
* @param id
*/
@GetMapping("get3/{id}")
public void get3(@PathVariable("id") Integer id){
System.out.println(id);
}
- @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); }
响应
- 响应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);
}
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);
}