个人简介
👀个人主页: 前端杂货铺
🙋♂️学习方向: 主攻前端方向,正逐渐往全干发展
📃个人状态: 研发工程师,现效力于中国工业软件事业
🚀人生格言: 积跬步至千里,积小流成江海
🥇推荐学习:🍍前端面试宝典 🍉Vue2 🍋Vue3 🍓Vue2/3项目实战 🥝Node.js实战 🍒Three.js
🌕个人推广:每篇文章最下方都有加入方式,旨在交流学习&资源分享,快加入进来吧
内容 | 参考链接 |
---|---|
Maven | 概念、IDEA集成、Maven坐标、依赖配置、依赖传递、排除依赖、依赖范围、生命周期 |
文章目录
前言
大家好,这里是前端杂货铺。
本篇文章我们学习如何借助 SpringBoot 实现基本的请求和响应。
简单参数
原始方式获取请求参数
下面这个是比较原始的写法。
公共接口类 HttpServletRequest 继承自 ServletRequest。客户端浏览器发出的请求被封装成为一个 HttpServletRequest 对象。
通过 getParameter() 方法能拿到从浏览器端传递的参数。
java
package com.zahuopu.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("/simpleParam")
public String simpleParam(HttpServletRequest request) {
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
int age = Integer.parseInt(ageStr);
System.out.println(name + ":" + age);
return "OK";
}
}
接下来,在浏览器打开 http://localhost:8080/simpleParam?name=zahuopu&age=18
网址,或使用 postman / apipost 等接口测试工具测试:
浏览器查看:

接口测试工具查看:

idea 控制台输出:

SpringBoot 接收简单参数
我们既然都使用了 SpringBoot,当然可以使用它自带的一些写法(直接通过参数映射接收,此时需注意 请求参数名与方法形参变量名相同),接下来请看代码...
java
package com.zahuopu.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("/simpleParam")
public String simpleParam(String name, Integer age) {
System.out.println(name + ": " + age);
return "OK";
}
}

@RequestParam 注解
当方法形参名称与请求参数名称不匹配时,我们可以通过 @RequestParam
注解完成映射。
该注解的 required 属性默认是 true,代表请求参数必须传递。可以手动改为 false,此时该属性可以不传递。
java
package com.zahuopu.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("/simpleParam")
public String simpleParam(@RequestParam(name = "name") String username, Integer age) {
System.out.println(username + ": " + age);
return "OK";
}
}

实体参数
如果请求的参数太多,我们可以使用实体对象参数。
规则:请求参数名与形参对象属性名相同,即可直接接收。
下面我们看个小例子,我们创建一个 User 类,里面定义 name 和 age 属性,并添加 get set 方法并重写 toString() 方法。再创建一个 Address 类,存放省份和城市。具体代码如下...
com.zahuopu.controller.RequestController
java
package com.zahuopu.controller;
import com.zahuopu.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("complexPojo")
public String complexPojo(User user) {
System.out.println(user);
return "OK";
}
}
com.zahuopu.pojo.User
java
package com.zahuopu.pojo;
public class User {
private String name;
private Integer age;
private Address address;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
com.zahuopu.pojo.Address
java
package com.zahuopu.pojo;
public class Address {
private String province;
private String city;
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
'}';
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
接口测试工具

idea 打印的内容

数组集合参数
数组:请求参数名与形参中数组变量名相同,可以直接使用数组封装。
集合:请求参数名与形参中集合变量名相同,通过 @RequestParam 绑定参数关系。
java
package com.zahuopu.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class RequestController {
@RequestMapping("/arrayParam")
public String arrayParam(String[] hobby) {
System.out.println(Arrays.toString(hobby));
return "OK";
}
@RequestMapping("/listParam")
public String listParam(@RequestParam List<String> hobby) {
System.out.println(hobby);
return "OK";
}
}



日期参数
使用 @DateTimeFormat 注解完成日期参数格式转换。
java
package com.zahuopu.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@RestController
public class RequestController {
@RequestMapping("/dateParam")
public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime) {
System.out.println(updateTime);
return "OK";
}
}


JSON 参数
JSON 参数:JSON 数据键名与形参对象属性名相同,定义 POJO 类型形参即可接收参数,需要使用 @RequestBody 标识。
java
package com.zahuopu.controller;
import com.zahuopu.pojo.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("/jsonParam")
public String jsonParam(@RequestBody User user) {
System.out.println(user.toString());
return "OK";
}
}


路径参数
通过请求 URL 直接传递参数,使用 {...} 来标识该路径参数,需要使用 @PathVariable 获取路径参数。
java
package com.zahuopu.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class RequestController {
@RequestMapping("/path/{id}/{name}")
public String pathParam(@PathVariable Integer id, @PathVariable String name) {
System.out.println(id + ":" + name);
return "OK";
}
}


统一响应结果
@RestController 注解的底层实现其实是有好几个注解的。
@ResponseBody 的作用是将方法返回值直接响应,若返回值类型是 实体对象 / 集合,则转 JSON 格式响应。

统一响应结果:在响应数据时,我们可以封装一个类,进行处理响应数据。
com.zahuopu.pojo.Result.java
java
package com.zahuopu.pojo;
public class Result {
private Integer code; // 1 成功 0 失败
private String msg; // 提示信息
private Object data; // 响应数据
public Result() {
}
public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static Result success(Object data) {
return new Result(1, "success", data);
}
public static Result success() {
return new Result(1, "success", null);
}
public static Result error(String msg) {
return new Result(0, msg, null);
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
com.zahuopu.controller.ResponseController.java
java
package com.zahuopu.controller;
import com.zahuopu.pojo.Address;
import com.zahuopu.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ResponseController {
@RequestMapping("/hello")
public Result hello() {
return Result.success("Hello World!");
}
@RequestMapping("/getAddr")
public Result getAddr() {
Address addr = new Address();
addr.setProvince("山东");
addr.setCity("济南");
return Result.success(addr);
}
@RequestMapping("/listAddr")
public Result listAddr() {
List<Address> list = new ArrayList<>();
Address addr = new Address();
addr.setProvince("山东");
addr.setCity("济南");
Address addr2 = new Address();
addr2.setProvince("河南");
addr2.setCity("郑州");
list.add(addr);
list.add(addr2);
return Result.success(list);
}
}
下面是各个请求响应的数据:



总结
本篇文章我们认识了 如何使用 SpringBoot 进行基本的请求响应操作。并认识了多种传参方式,包括简单参数、实体参数、数组集合参数、日期参数、JSON参数、路径参数等,并在最后进行了统一响应结果的封装处理!
好啦,本篇文章到这里就要和大家说再见啦,祝你这篇文章阅读愉快,你下篇文章的阅读愉快留着我下篇文章再祝!
参考资料:
