Several ways for springboot to receive front-end parameters

Table of contents

The first one: specify parameters directly in the method

Second type: use @requesrParam annotation

Third method: based on @pathVariable 

The fourth method: based on @ResquestBody

Before we start, we need to make some preparations, create a database, springboot project, add dependencies, and configuration files. The technologies used include mybatisplus, springboot, maven, and mysql.

First, create a database table

 Then, create a springboot project, import relevant dependencies, and write relevant configurations

Among them, maven related dependencies

 application.yml configuration file, I used mybatisplus, which requires related dependencies and configurations.

In order to facilitate front-end and back-end interaction, I used json for front-end and back-end data transfer, and the Java backend performed data encapsulation.

 The project package structure is shown in the figure

Okay, the preparation work is basically completed here. Let’s explore how the backend receives the parameters given to us by the frontend.

The first one: specify parameters directly in the method

We write a method in UserController to get a user object through user name and password.

Add methods to the interface and override them in the implementation class

 

 Use apifox to test, you can see that we have got the return result

We used logs in the UserController to record the query process. You can see that the username is output in the console, indicating that we have obtained this parameter. However, this method has several flaws. First, we need a parameter in the body in apifox. Firstly, the positions of username and password cannot be wrong. Secondly, the parameter names must be consistent. If they are different, the parameter cannot be received.

Obviously, this method of receiving parameters has many flaws, so we need to improve it.

Second type: use @requesrParam annotation

 

This method solves the shortcomings of the first method. It does not require one-to-one correspondence between parameters, nor does it require consistent names. In the annotations, you can fill in any name at will and it will correspond.

Third method: based on @pathVariable

 

We only need to add parameters to the request path, but note that the parameters added to the path need to be spliced ​​with parentheses, and must have the same name as the corresponding parameter in the method.

The fourth method: based on @ResquestBody

This annotation is used most frequently and can automatically encapsulate parameters into an object.

 With the object encapsulated by @ResquestBody, we can completely retain all the corresponding attributes in the user object. Unassigned attributes should be empty, and the object can be modified, assigned and extracted through the set and get methods.

Guess you like

Origin blog.csdn.net/weixin_69764845/article/details/131031933