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?

PHPz
PHPzforward
2023-05-11 12:28:061283browse

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";
    }
}

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";
    }
}

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";
    }
}

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";
}

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";
    }

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";
    }
}

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;
    .....
}

method code

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

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";
    }
}

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";
    }
}

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";
    }
}

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 方法
}
@RestController
public class RequestController {
    //JSON参数
    @RequestMapping("/jsonParam")
    public String jsonParam(@RequestBody User user){
        System.out.println(user);
        return "OK";
    }
}

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";
    }
}

传递多个路径参数:

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

响应:

前面我们学习过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;
    }
}

在服务响应了一个对象或者集合,那私前端获取到的数据是什么样子的呢?我们使用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);
    }
}

改造后的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);
    }
}

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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete