【SpringBoot web-2】web项目参数传递


新建一个项目,具体步骤可参照上文:SpringBoot系列(二) https://blog.csdn.net/mu_wind/article/details/94294138#_189

项目依赖

pom.xml 中添加依赖(添加此依赖并安装插件后,在实体类中使用@data注解,可以省略set和get方法):

<!--Web 依赖-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--省略setget方法-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

项目结构

1、启动类:

@SpringBootApplication
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2、实体类 Student:

package com.example.demo.model;

import lombok.Data;

@Data
public class Student {
    private String name;
    private int age;
    private int score;
}

3、接口类 StudentController:

package com.example.demo.controller;

@RestController
public class StudentController {
    @RequestMapping(name="/getStudent", method= RequestMethod.POST)
    public User getStudent() {
        Student student = new Student();
        student.setName("小红");
        student.setAge(12);
        student .setScore(560);
        return user;
    }
}

@RestController 注解相当于 @ResponseBody + @Controller 合在一起的作用,如果 Web 层的类上使用了 @RestController 注解,就代表这个类中所有的方法都会以 JSON 的形式返回结果,也相当于 JSON 的一种快捷使用方式;
@RequestMapping(name="/getStudent", method= RequestMethod.POST),以 /getStudent 的方式去请求,method= RequestMethod.POST 是指只可以使用 Post 的方式去请求,如果使用 Get 的方式去请求的话,则会报 405 不允许访问的错误。

4、测试类:
在 test 包下新建 ControllerTest 测试类,对 getUser() 方法使用MockMvc进行测试。

package com.example.demo;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Test
    public void getStudent() throws Exception{
        String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/getStudent"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("result : "+responseString);
    }
}

运行Test,得到结果:

result : {"name":"小红","age":12,"score":650}

说明 Spring Boot 自动将 Student对象转成了 JSON 进行返回。那么如果返回的是一个 list 呢?

@RequestMapping("/getStudents")
public List<Student> getStudents() {
    List<Student> students = new ArrayList<>();
    Student student1 = new Student();
    student1.setName("王小宏");
    student1.setAge(31);
    student1.setScore(635);
    students.add(student1);

    Student student2 = new Student();
    student2.setName("宋小专");
    student2.setAge(27);
    student2.setScore(522);
    students.add(student2);
    return students;
}

添加测试方法:

@Test
public void getStudents() throws Exception{
    String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/getStudents"))
            .andReturn().getResponse().getContentAsString();
    System.out.println("result : "+responseString);
}

运行测试结果,得到结果:

result : [{"name":"王小宏","age":31,"score":635},{"name":"宋小专","age":27,"score":522}]

请求传参

前端浏览器和后端服务器正是依赖交互过程中的参数完成了诸多用户操作行为,因此参数的传递和接收是一个 Web 系统最基础的功能。SpringBoot对参数接收做了很好的支持,内置了很多种参数接收方式,提供一些注解来帮助限制请求的类型、接收不同格式的参数等。
Get与Post:
如果我们希望一个接口以Post方式访问,在方法上添加一个配置(method= RequestMethod.POST)即可:

@RequestMapping(name="/getStudent", method= RequestMethod.POST)
public User getStudent() {
    ...
}

如果以Get方法请求该接口,将得到【Request method ‘GET’ not supported】的报错。
同样,如果是GET 请求,method 设置为:method= RequestMethod.GET;如果不进行设置默认两种方式的请求都支持。

请求传参一般分为 URL 地址传参和表单传参两种方式,都以键值对的方式将参数传递到后端。作为后端程序不用关注前端采用的那种方式,只需要根据参数的键来获取值。

通过 URL 传参

只要后端处理请求的方法中存在参数键相同名称的属性,在请求的过程中 Spring 会自动将参数值赋值到属性中,最后在方法中直接使用即可。

@RequestMapping(name = "/test", method = RequestMethod.GET)
public String test(String name) {
    return name;
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void getStudents() throws Exception {
        String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/test?name=xiaohong"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("result : " + responseString);
    }
}

结果:

result : xiaohong

另一种方式:

@RequestMapping(value="test/{name}", method=RequestMethod.GET)
public String get(@PathVariable String name) {
    return name;
}

这样的写法,传参地址栏会更加美观一些。
测试:

@Test
public void getStudents() throws Exception {
    String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/test/xiaohong"))
            .andReturn().getResponse().getContentAsString();
    System.out.println("result : " + responseString);
}

结果同上例。

表单传参

通过表单传参一般适用于Post请求。例如下面这个接口,只要前端请求带入name和age两个参数,就能被解析到。

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String get(String name, String age) {
    return "姓名:" + name + ",年龄:" + age;
}

使用Jmeter发送一个接口请求:
在这里插入图片描述
结果:
姓名:小宏,年龄:31

实体传参

有时候前端直接提交一个form表单,传入后端的参数就是JSON格式的,这种参数后端如何接收和处理呢,下面进行示范:
首先,在pom.xml中引入fastjson依赖

<dependency>
	<groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
 </dependency>

后端接口:


测试:
Jmeter中发送一个接口请求:
在这里插入图片描述
在这里插入图片描述
结果同上例。

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
springboot vue-simple-uploader 是一个前后端分离的文件上传插件,在使用前需要进行相关配置和代码的编写。 首先,在后端部分,我们使用的是Spring Boot框架。需要导入spring-boot-starter-web依赖,并在配置文件中配置相关参数,例如设置文件上传临时目录、文件上传大小限制等。然后,我们需要编写一个处理文件上传请求的Controller类,使用@RequestBody注解接收前端传递的文件信息,并使用multipartFile.transferTo()方法保存文件到指定目录中。 在前端部分,我们使用的是Vue.js框架,并引入vue-simple-uploader插件。首先,我们需要安装该插件,可以使用npm安装或者直接引入插件的CDN地址。然后,在Vue实例中,我们可以通过配置uploaderOptions对象来进行插件的相关配置,例如设置上传的url、自定义headers、文件的最大数量和大小限制等。然后,在需要上传文件的组件中,我们可以通过引入uploader组件,并使用v-model绑定上传的文件列表。 通过上述配置和代码编写,我们就可以实现前后端分离的文件上传功能了。当用户选择上传的文件后,前端会将文件信息发送给后端,后端接收到请求后进行文件保存操作,并返回相应的结果给前端,例如文件的保存路径或者上传成功的提示信息。 总结一下,springboot vue-simple-uploader是一个支持前后端分离的文件上传插件,通过在后端配置文件上传参数和编写Controller类,在前端通过配置uploaderOptions对象和使用uploader组件,我们可以实现文件的上传和保存功能。这样,我们就可以方便地在Spring Boot和Vue.js项目中实现文件上传的需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云深i不知处

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值