postman测试@pathvariable,@requestparam,@requestbody发送情况

postman测试@pathvariable,@requestparam,@requestbody发送情况

1、三种方式简单说明

1.1、@Pathvariable

通过占位符的方式获取入参,前端示例:url:http://localhost:8080/system/student/${stuSno}
也即是从路径里面去获取变量
后端:

    /**
     * @param stuSno 学号
     * @return 学生信息
     * @description 根据主键获取学生信息
     */
    @GetMapping("/selectByPrimaryKey/{stuSno}")
    public Student selectByPrimaryKey(@PathVariable String stuSno) {
        return studentService.selectByPrimaryKey(stuSno);
    }

这种情况是方法参数名称和需要绑定的url中变量名称一致时
若是若方法参数名称和需要绑定的url中变量名称不一致时
后端:

/**
 * @param stuSno 学号
 * @return 学生信息
 * @description 根据主键获取学生信息
 */
@GetMapping("/selectByPrimaryKey/{stuSno}")
public Student selectByPrimaryKey(@PathVariable("stuSno") String sno) {
    return studentService.selectByPrimaryKey(stuSno);
}

注意:前端传参的URL于后端@RequestMapping的URL必须相同且参数位置一一对应,否则前端会找不到后端地址

1.2、@RequestParam

  1. 作用
    将请求参数绑定在控制层(controller)方法参数【springmvc注解】
  2. 语法
@RequestParam(value="参数名",required="true/false",default="")

在这里插入图片描述

value:表示前端传过来的值名称,如果你不设置,那就默认使用服务端使用的参数名称(stuSno)
不设置:
前端:在这里插入图片描述

http://localhost:8081/student/selectByPrimaryKey1?stuSno=0001

后端:
在这里插入图片描述

public Student selectByPrimaryKey1(@RequestParam String stuSno) {

设置
前端:
在这里插入图片描述

http://localhost:8081/student/selectByPrimaryKey1?sno=0001

后端:
在这里插入图片描述
此时@requestParam中value=“sno” value可以省略 直接输入“sno”,类似于@RequestMapping

    public Student selectByPrimaryKey1(@RequestParam("sno") String stuSno) {

这时候前端传sno并非stuSno,需要在@requestParam中value设置sno
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错
在这里插入图片描述

2021-08-15 02:26:30.495  WARN 4736 --- [nio-8081-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'sno' for method parameter type String is not present]

defaultValue:默认参数值,如果设置了该值,required=true将失效,自动变为false,如果没有传该参数,使用默认值;比如说此时 后端直接写成 defaultValue=“0001”
在这里插入图片描述在这里插入图片描述

  1. 示例说明
    后端controller
    /**
     * @param stuSno 学号
     * @return 学生信息
     * @description 根据主键获取学生信息
     */
    @GetMapping("/selectByPrimaryKey")
    public Student selectByPrimaryKey1(@RequestParam(value = "sno",defaultValue = "0001",required = false) String stuSno) {
        return studentService.selectByPrimaryKey(stuSno);
    }

前端暂时使用 postman
在这里插入图片描述

1.3、@RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)

  1. @RequestBody直接以String接收前端传过来的json数据
    后端代码
    /**
     * @param stuSno 学号
     * @return 学生信息
     * @description 根据主键获取学生信息
     */
    @GetMapping("/selectByPrimaryKey3")
    public Student selectByPrimaryKey2(@RequestBody String jsonString) {
        // 使用fastjson解析json格式字符串为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        // 获取学号
        String stuSno = jsonObject.getString("stuSno");
        return studentService.selectByPrimaryKey(stuSno);
    }

前端postman
在这里插入图片描述
需要通过fastjson转换json字符串为json对象从而获取相应的值,否则报错
在这里插入图片描述

  1. @RequestBody以简单对象接收前端传过来的json数据
    实体类
package com.geekmice.springbootrequestparam.pojo;


import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;

public class Student implements Serializable {

    private String stuSno;
    private String stuName;
    private String stuBorn;
    private String stuSex;

    public String getStuSno() {
        return stuSno;
    }

    public void setStuSno(String stuSno) {
        this.stuSno = stuSno;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuBorn() {
        return stuBorn;
    }

    public void setStuBorn(String stuBorn) {
        this.stuBorn = stuBorn;
    }

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuSno='" + stuSno + '\'' +
                ", stuName='" + stuName + '\'' +
                ", stuBorn='" + stuBorn + '\'' +
                ", stuSex='" + stuSex + '\'' +
                '}';
    }
}

dao层

    /**
     * @param student 学生信息
     * @return 返回学生信息
     * @description 根据学生对象获取学生信息
     */
    List<Student> selectByPrimaryKeySelective(Student student);

xml

<!--获取学生信息-->
    <select id="selectByPrimaryKeySelective" resultType="student" parameterType="student">
        select
        <include refid="Base_Column_List"/>
        from student
        <where>
            <if test="stuSno != '' and stuSno != null">
                stu_sno = #{stuSno}
            </if>
            <if test="stuName != '' and stuName != null">
                and stu_name = #{stuName}
            </if>
            <if test="stuBorn != '' and stuBorn != null">
                and stu_born = #{stuBorn}
            </if>
            <if test="stuSex != '' and stuSex != null">
                and stu_sex = #{stuSex}
            </if>
        </where>
    </select>

service

    /**
     * @description 根据学生对象获取学生信息
     * @param student 学生信息
     * @return 返回学生信息
     */
    List<Student> selectByPrimaryKeySelective(Student student);
    @Override
    public List<Student> selectByPrimaryKeySelective(Student student) {
        return studentDao.selectByPrimaryKeySelective(student);
    }

controller

    /**
     * @param student 学生对象
     * @return 获取对应学生信息
     * @description 用户选择获取对应的学生信息
     */
    @PostMapping("/selectByPrimaryKeySelective")
    public List<Student> selectByPrimaryKeySelective(@RequestBody Student student) {
        return studentService.selectByPrimaryKeySelective(student);
    }

postman效果
在这里插入图片描述

  1. @RequestBody以复杂对象接收前端传过来的json数据
    复杂对象:Tim
package com.geekmice.springbootrequestparam.pojo;

import java.util.List;

/**
 * @author pmb
 * @create 2021-08-15-4:34
 */
public class Tim {
    // 团队id
    private Integer id;

    // 团队名字
    private String timName;

    // 获得荣誉
    private List<String> honors;

    // 团队成员
    private List<Student> studentList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTimName() {
        return timName;
    }

    public void setTimName(String timName) {
        this.timName = timName;
    }

    public List<String> getHonors() {
        return honors;
    }

    public void setHonors(List<String> honors) {
        this.honors = honors;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    @Override
    public String toString() {
        StringBuffer stringHonor = new StringBuffer("荣誉开始:。。。");
        for (String str : honors) {
            stringHonor.append(str);
            stringHonor.append("+");
        }
        StringBuffer stringTim = new StringBuffer("团队成员开始:。。。");
        for (Student student : studentList) {
            stringTim.append(student);
            stringTim.append("-");
        }
        stringHonor.append(stringTim);
        return stringHonor.toString();
    }
}

在这里插入图片描述
postman
在这里插入图片描述

  1. @RequestBody与简单的@RequestParam()同时使用

controller
在这里插入图片描述

postman在这里插入图片描述

  1. @RequestBody与复杂的@RequestParam()同时使用
    controller
    在这里插入图片描述

postman
在这里插入图片描述

  1. @RequestBody接收请求体中的json数据;不加注解接收URL中的数据并组装为对象
    在这里插入图片描述

在这里插入图片描述

3、不同之处&应用场景

我认为在单个参数提交 API 获取信息的时候,直接放在 URL 地址里,也就是使用 URI 模板的方式是非常方便的,而不使用 @PathVariable 还需要从 request 里提取指定参数,多一步操作,所以如果提取的是多个参数,而且是多个不同类型的参数,我觉得应该使用其他方式,也就是 @RequestParam

在这里插入图片描述

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Spring Boot和MyBatis搭建一个web项目,并自定义学生表,并运用注解完成增删改查接口。同时,通过拦截器来打印每个接口的用时。 首先,确保你已经配置好了Spring Boot和MyBatis的环境。然后,创建一个名为Student的实体类,包含学生的信息。 ```java public class Student { private Long id; private String name; private Integer age; // 省略getter和setter方法 } ``` 接下来,创建一个名为StudentMapper的接口,用于定义数据库操作的方法。 ```java @Mapper public interface StudentMapper { @Insert("INSERT INTO student(name, age) VALUES(#{name}, #{age})") @Options(useGeneratedKeys = true, keyProperty = "id") int insert(Student student); @Delete("DELETE FROM student WHERE id = #{id}") int deleteById(Long id); @Update("UPDATE student SET name = #{name}, age = #{age} WHERE id = #{id}") int update(Student student); @Select("SELECT * FROM student WHERE id = #{id}") Student findById(Long id); @Select("SELECT * FROM student") List<Student> findAll(); } ``` 然后,创建一个名为StudentController的控制器类,用于处理请求。 ```java @RestController @RequestMapping("/students") public class StudentController { private final StudentMapper studentMapper; public StudentController(StudentMapper studentMapper) { this.studentMapper = studentMapper; } @PostMapping public Long createStudent(@RequestBody Student student) { studentMapper.insert(student); return student.getId(); } @DeleteMapping("/{id}") public void deleteStudent(@PathVariable Long id) { studentMapper.deleteById(id); } @PutMapping("/{id}") public void updateStudent(@PathVariable Long id, @RequestBody Student student) { student.setId(id); studentMapper.update(student); } @GetMapping("/{id}") public Student getStudent(@PathVariable Long id) { return studentMapper.findById(id); } @GetMapping public List<Student> getAllStudents() { return studentMapper.findAll(); } } ``` 接下来,创建一个名为LoggingInterceptor的拦截器类,用于打印每个接口的用时。 ```java @Component public class LoggingInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.setAttribute("startTime", System.currentTimeMillis()); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long startTime = (long) request.getAttribute("startTime"); long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; String requestURI = request.getRequestURI(); System.out.println(requestURI + " executed in " + elapsedTime + "ms"); } } ``` 最后,配置拦截器和MyBatis动态标签。 ```java @Configuration public class WebConfig implements WebMvcConfigurer { private final LoggingInterceptor loggingInterceptor; public WebConfig(LoggingInterceptor loggingInterceptor) { this.loggingInterceptor = loggingInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loggingInterceptor); } } @MapperScan("com.example.mapper") public class MyBatisConfig { } ``` 这样,你就完成了使用Spring Boot和MyBatis搭建web项目,并通过注解完成增删改查接口,并通过拦截器打印每个接口的用时。同时,使用MyBatis的动态标签可以完成判断查询和批量插入并获取自增主键id的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值