Table of Contents
Request
1. Simple parameters
2. Entity parameters
3. Array collection parameters
4, date parameter
5. JSON parameters
6、路径参数(开发中使用的模式)
统一响应结果
Home Java javaTutorial How does SpringBoot obtain front-end parameters and how to respond uniformly?

How does SpringBoot obtain front-end parameters and how to respond uniformly?

May 11, 2023 pm 12:28 PM
springboot

Request

The six ways SpringBoot accepts front-end parameters. First of all, because the request sent from the front-end without an interface can only be sent from the address bar and can only be a Get request, in order to test other requests, so We use a tool ->Postman. Postman is a powerful Chrome plug-in for debugging web pages and sending HTTP requests to web pages.

The parameters passed from the front desk are roughly divided into six types. Let’s do a demonstration and study one by one: review it before the demonstration. There is no way to obtain the front desk parameters through SpringBoot, and they are obtained through the request object.

@RestController
public class RequestController {
    //原始方式
    @RequestMapping("/simpleParam")
    public String simpleParam(HttpServletRequest request){
        // http://localhost:8080/simpleParam?name=Tom&age=10
        // 请求参数: name=Tom&age=10   (有2个请求参数)
        // 第1个请求参数: name=Tom   参数名:name,参数值:Tom
        // 第2个请求参数: age=10     参数名:age , 参数值:10

        String name = request.getParameter("name");//name就是请求参数名
        String ageStr = request.getParameter("age");//age就是请求参数名

        int age = Integer.parseInt(ageStr);//需要手动进行类型转换
        System.out.println(name+"  :  "+age);
        return "OK";
    }
}
Copy after login

In the Springboot environment, the original API is encapsulated, and the form of receiving parameters is simpler. If it is a simple parameter, the parameter name is the same as the formal parameter variable name, and the parameter can be received by defining a formal parameter with the same name.

1. Simple parameters

@RestController
public class RequestController {
        // http://localhost:8080/simpleParam?name=Tom&age=10
    // 第1个请求参数: name=Tom   参数名:name,参数值:Tom
    // 第2个请求参数: age=10     参数名:age , 参数值:10
    
    //springboot方式
    @RequestMapping("/simpleParam")
    public String simpleParam(String name , Integer age ){//形参名和请求参数名保持一致
        System.out.println(name+"  :  "+age);
        return "OK";
    }
}
Copy after login

If the backend needs it but the frontend does not pass the corresponding parameters, null will be returned at this time

The parameter name passed by the current frontend and the parameter accepted by the backend When the method parameter list is inconsistent, you can specify it through @RequestParam (" ")

@RestController
public class RequestController {
    // http://localhost:8080/simpleParam?name=Tom&age=20
    // 请求参数名:name

    //springboot方式
    @RequestMapping("/simpleParam")
    public String simpleParam(@RequestParam("name") String username , Integer age ){
        System.out.println(username+"  :  "+age);
        return "OK";
    }
}
Copy after login

In addition, the required attribute in @RequestParam defaults to true (the default value is also true), which means that the request parameter must be passed. If If not passed, an error will be reported. If the parameter is optional, the required attribute can be set to false

The code is as follows:

@RequestMapping("/simpleParam")
public String simpleParam(@RequestParam(name = "name", required = false) String username, Integer age){
    System.out.println(username+ ":" + age);
    return "OK";
}
Copy after login

This annotation also has another parameter, which is defaultValue, indicating that if the front desk does not pass it The parameter defaults to the currently specified value.

    @RequestMapping("/simpleParam")
    public String simpleParam(@RequestParam(name = "name", required = false,defaultValue ="匿名用户") String userName, Integer age) {
        
//        打印输出
        System.out.println(userName+"----"+age);
        return "ok";
    }
Copy after login

2. Entity parameters

Simple entity object:

When using simple parameters as the data transmission method, how many request parameters are passed by the front end, and the backend controller method How many formal parameters should be written in. If there are many request parameters, receiving each parameter one by one through the above method will be more cumbersome.

At this point, we can consider encapsulating the request parameters into an entity class object. To complete data encapsulation, you need to abide by the following rules: The request parameter name is the same as the attribute name of the entity class

The requirement is that the parameters passed from the front desk must have the same name as the parameters in the object, in order same.

@RestController
public class RequestController {
    // http://localhost:8080/simpleParam?name=Tom&age=20
    
    //实体参数:简单实体对象  User有两个属性,一个是name 一个是age,这样Spring就会自动完成赋值
    @RequestMapping("/simplePojo")
    public String simplePojo(User user){
        System.out.println(user);
        return "OK";
    }
}
Copy after login

Complex entity object: object within object

For example, there is another field in User: Address, and this class has two properties. At this time, the parameters need to be passed to the front desk. Change, the background still uses User to accept

public class User {
    private String name;
    private Integer age;
    private Address address; //地址对象
    .....
}


public class Address {
    private String province;
    private String city;
    .....
}
Copy after login

method code

@RestController
public class RequestController {
    //实体参数:复杂实体对象
    @RequestMapping("/complexPojo")
    public String complexPojo(User user){
        System.out.println(user);
        return "OK";
    }
}
Copy after login

How does SpringBoot obtain front-end parameters and how to respond uniformly?

3. Array collection parameters

Usage scenarios of array collection parameters: In the HTML form, there is a form item that supports multiple selections (checkboxes) and can submit multiple selected values.

xxxxxxxx?hobby=game&hobby=java

There are two ways for the back-end program to receive the above multiple values:

  • Array

  • Collection

Array parameters: The request parameter name is the same as the formal parameter group name and there are multiple request parameters. Just define the array type formal parameter. Receive parameters

@RestController
public class RequestController {
    //数组集合参数
    @RequestMapping("/arrayParam")
    public String arrayParam(String[] hobby){
        System.out.println(Arrays.toString(hobby));
        return "OK";
    }
}
Copy after login

Collection parameters:The request parameter name is the same as the formal parameter collection object name and there are multiple request parameters, @RequestParam binds parameter relationship

By default, multiple values ​​with the same parameter name in the request are encapsulated into an array. If you want to encapsulate it into a collection, you need to use @RequestParam to bind the parameter relationship

Controller method:

@RestController
public class RequestController {
    //数组集合参数
    @RequestMapping("/listParam")
    public String listParam(@RequestParam List<String> hobby){
        System.out.println(hobby);
        return "OK";
    }
}
Copy after login

4, date parameter

The above demonstrations are all common Parameters, in some special requirements, may involve the encapsulation of date type data (in fact, we generally store strings and do not transfer them around, so we understand here). For example, the following requirements:

How does SpringBoot obtain front-end parameters and how to respond uniformly?

Because the date formats are various (such as: 2022-12-12 10:05:45, 2022/12/12 10:05: 45), then when encapsulating date type parameters, the date format needs to be set through the @DateTimeFormat annotation and its pattern attribute.

  • #@DateTimeFormat annotation, which date format is specified in the pattern attribute, the front-end date parameter must be passed in the specified format.

  • In the backend controller method, you need to use the Date type LocalDateT or LocalDateTime type to encapsulate the passed parameters.

Controller method:

@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";
    }
}
Copy after login

5. JSON parameters

When learning front-end technology, we have talked about JSON, and in the front-end and back-end During interaction, if the parameters are more complex, the front-end and back-end will use JSON format data for transmission. (JSON is the most commonly used front-end and back-end data interaction method in development). In fact, we will also see that if the backend returns data to the frontend, some are strings, some are collections, and some are JSON, then the frontend will parse it. It's very troublesome. Later, an entity class is used to store all the data, and then the object is returned. In this way, the front desk only needs to process JSON when accepting it. At the end of the note, I will mention

, which is introduced below in Postman How to send JSON data:

How does SpringBoot obtain front-end parameters and how to respond uniformly?

服务端Controller方法接收JSON格式数据:

  • 传递json格式的参数,在Controller中会使用实体类进行封装。

  • 封装规则:JSON数据键名与形参对象属性名相同,定义POJO类型形参即可接收参数。需要使用 @RequestBody标识。

@RequestBody注解:将JSON数据映射到形参的实体类对象中(JSON中的key和实体类中的属性名保持一致)

通过添加@RequestBody注解Spring可以自动的将JSON转换为对象.

实体类:

public class User {
    private String name;
    private Integer age;
    private Address address;
    
    //省略GET , SET 方法
}
Copy after login
@RestController
public class RequestController {
    //JSON参数
    @RequestMapping("/jsonParam")
    public String jsonParam(@RequestBody User user){
        System.out.println(user);
        return "OK";
    }
}
Copy after login

6、路径参数(开发中使用的模式)

传统的开发中请求参数是放在请求体(POST请求)传递或跟在URL后面通过?key=value的形式传递(GET请求)。

在现在的开发中,经常还会直接在请求的URL中传递参数。例如:

http://localhost:8080/user/1
http://localhost:880/user/1/0

上述的这种传递请求参数的形式呢,我们称之为:路径参数。

学习路径参数呢,主要掌握在后端的controller方法中,如何接收路径参数。

路径参数:

  • 前端:通过请求URL直接传递参数

  • 后端:使用{…}来标识该路径参数,需要使用@PathVariable获取路径参数

Controller方法:

@RestController
public class RequestController {
    //路径参数
    @RequestMapping("/path/{id}")
    public String pathParam(@PathVariable Integer id){
        System.out.println(id);
        return "OK";
    }
}
Copy after login

传递多个路径参数:

@RestController
public class RequestController {
    //路径参数  前台路径  xxxx/path/12/jack
    @RequestMapping("/path/{id}/{name}")
    public String pathParam2(@PathVariable Integer id, @PathVariable String name){
        System.out.println(id+ " : " +name);
        return "OK";
    }
}
Copy after login

响应:

前面我们学习过HTTL协议的交互方式:请求响应模式(有请求就有响应)

那么Controller程序呢,除了接收请求外,还可以进行响应。先说一下使用到的注解:

@ResponseBody

  • 类型:方法注解、类注解

  • 位置:书写在Controller方法上或类上

  • 作用:将方法返回值直接响应给浏览器

如果返回值类型是实体对象/集合,将会转换为JSON格式后在响应给浏览器

在我们前面所编写的controller方法中,都已经设置了响应数据。看一下类的注解@RestController, 这个注解是一个复合注解,里面包括了 @ResponseBody

How does SpringBoot obtain front-end parameters and how to respond uniformly?

结论:在类上添加@RestController就相当于添加了@ResponseBody注解。

类上有@RestController注解或@ResponseBody注解时:表示当前类下所有的方法返回值做为响应数据方法的返回值,如果是一个POJO对象或集合时,会先转换为JSON格式,在响应给浏览器

下面我们来测试下响应数据:

@RestController
public class ResponseController {
    //响应字符串
    @RequestMapping("/hello")
    public String hello(){
        System.out.println("Hello World ~");
        return "Hello World ~";
    }
    //响应实体对象
    @RequestMapping("/getAddr")
    public Address getAddr(){
        Address addr = new Address();//创建实体类对象
        addr.setProvince("广东");
        addr.setCity("深圳");
        return addr;
    }
    //响应集合数据
    @RequestMapping("/listAddr")
    public List<Address> 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 list;
    }
}
Copy after login

在服务响应了一个对象或者集合,那私前端获取到的数据是什么样子的呢?我们使用postman发送请求来测试下。测试效果如下:

How does SpringBoot obtain front-end parameters and how to respond uniformly?

How does SpringBoot obtain front-end parameters and how to respond uniformly?

统一响应结果

可能大家会发现,我们在前面所编写的这些Controller方法中,返回值各种各样,没有任何的规范。

How does SpringBoot obtain front-end parameters and how to respond uniformly?

如果我们开发一个大型项目,项目中controller方法将成千上万,使用上述方式将造成整个项目难以维护。那在真实的项目开发中是什么样子的呢?

在真实的项目开发中,无论是哪种方法,我们都会定义一个统一的返回结果。方案如下:

How does SpringBoot obtain front-end parameters and how to respond uniformly?

这样前端只需要按照统一格式的返回结果进行解析(仅一种解析方案),就可以拿到数据。

统一的返回结果使用类来描述,在这个结果中包含:

  • 响应状态码:当前请求是成功,还是失败

  • 状态码信息:给页面的提示信息

  • 返回的数据:给前端响应的数据(字符串、对象、集合)

定义在一个实体类Result来包含以上信息。代码如下:

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(){
        return new Result(1,"success",null);
    }
    //查询 成功响应(把查询结果做为返回数据响应给前端)
    public static Result success(Object data){
        return new Result(1,"success",data);
    }
    //失败响应
    public static Result error(String msg){
        return new Result(0,msg,null);
    }
}
Copy after login

改造后的Controller:统一返回Result

@RestController
public class ResponseController { 
    //响应统一格式的结果
    @RequestMapping("/hello")
    public Result hello(){
        System.out.println("Hello World ~");
        //return new Result(1,"success","Hello World ~");
        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);
    }
}
Copy after login

How does SpringBoot obtain front-end parameters and how to respond uniformly?

How does SpringBoot obtain front-end parameters and how to respond uniformly?

The above is the detailed content of How does SpringBoot obtain front-end parameters and how to respond uniformly?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles