SpringBoot2 Parameter Management Practice: Input Input Input Input Input and Input Verification Methods

  • 2021-09-16 07:03:47
  • OfStack

Directory 1. Parameter management 2. Receive parameter 3. Response parameter 4. Parameter check 1. Reference 2. Common check method 5. Source code address

1. Parameter management

In the programming system, in order to write good code, the code will be standardized according to various design patterns, principles, constraints, etc., so as to improve the readability, reusability and modifiability of the code. In fact, I personally think that if the written code is very good, that is, other people's modification cannot destroy the original author's thinking and packaging, which should be a very high level.

But in daily development, Due to many objective factors, There is little time to constantly think and optimize the code, Therefore, we can only think about how to build the system code from the perspective of the actual situation, and ensure that we can read our own code in the future. In our own programming for several years, we will actually consider the following aspects: code level management, naming and annotation unification 1, reasonable design of business database, and clear parameter style.

Let's talk about parameter management here, focusing on three aspects: parameter entry, verification and parameter return.

How to understand the concept of code specification: that is, the constraints that most developers agree with and are willing to abide by, such as the management of projects by Spring framework and Mvc pattern, and the provisions for business development in Java Development Manual, the fundamental purpose of which is to avoid the code evolving into an unmaintainable state with the development of business.

2. Receive parameters

There are many ways to receive parameters, such as List, Map, Object, etc. However, in order to clarify the semantics of parameters, it is usually necessary to design the structure of parameter objects and comply with 1 specification, for example, explicitly prohibit Map from receiving parameters:

The Rest style accepts a single ID parameter:


@GetMapping("/param/single/{id}")
public String paramSingle (@PathVariable Integer id){
    return "Resp:"+id ;
}

Receives multiple specified parameters:


@GetMapping("/param/multi")
public String paramMulti (@RequestParam("key") String key, @RequestParam("var") String var){
    return "Resp:"+key+var ;
}

Based on Java wrapping object entry:


@PostMapping("/param/wrap")
public ParamIn paramWrap (@RequestBody ParamIn paramIn){
    return paramIn ;
}

--  Parameter object entity 
public class ParamIn {
    private Integer id ;
    private String key ;
    private String var ;
    private String name ;
}

These are several common ways to connect parameters in development, and the following habits are usually observed here:

Parameter semantics: clear the role of receiving parameters; Number limit: more than 3 parameters use wrapper objects; Avoid multiple interfaces using a single wrapper object as a parameter; Avoid wrapping the object body too complex;

There are no complicated constraints on parameter acceptance, On the whole, it is easier to abide by, The common problem is that when dealing with large subject objects, it is easy to produce a wrapper object that is reused in multiple places, which leads to many object field attributes. This situation is especially easy to occur in complex businesses. This kind of object is not conducive to the use of web layer interface, or objects are often mixed in business layer and interface layer;

It is a reasonable and common operation to encapsulate complex BO objects in the service layer to reduce the complexity of service management. It can be managed into the main body according to the interface functions in the web interface layer, and then transmitted into BO objects in the process of service implementation.

Avoid complex business wrapper objects floating in various layers. If multiple interfaces are all the same complex objects, it is easy for developers to be confused.

3. Response parameters

Parameter response is corresponding to parameter reception, which usually has clear constraint specifications: response subject data, response code and description information. Generally speaking, these are the three core elements.

Response parameter body:

Here, the use of generics is usually used to receive body data.


public class Resp<T> {

    private int code ;
    private String msg ;
    private T data ;

    public static <T> Resp<T> ok (T data) {
        Resp<T> result = new Resp<>(HttpStatus.OK);
        result.setData(data);
        return result ;
    }

    public Resp (HttpStatus httpStatus) {
        this.code = httpStatus.value();
        this.msg = httpStatus.getReasonPhrase();
    }

    public Resp(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}

Code status code

That is, interface status, it is recommended to refer to and abide by it HttpStatus The description of the status code in, which is a common specification for development. If it does not meet the business requirements, it can completely customize a set of response codes in an appropriate custom part of the code, but it is not necessary.

Msg description

Msg describing the response of the interface may be: success or failure, and more often, it is necessary to deal with the prompt information of business exception, such as the non-existence of single number, account freezing, etc. Usually, it is necessary to capture the prompt information from business exception and respond to the page, or the description that the entry parameter verification fails.

Data data

Interface response to the main data, different business response objects are definitely different, so here based on generic mechanism can be received, and then JSON format response page.

Reference case

Interface return parameter:


@PostMapping("/resp/wrap")
public Resp<KeyValue> respWrap (@RequestBody KeyValue keyValue){
    return Resp.ok(keyValue) ;
}

Response format:


{
   "code": 200,
   "msg": "OK",
   "data": {
       "key": "hello",
       "value": "world"
   }
}

4. Parameter verification

Parameter receiving and response are relatively not complicated, and it is difficult to deal with parameter verification: parameter entry constraint verification, service legitimacy verification, response parameter non-empty non-null verification, and other scenarios.

In the process of system operation, any parameters are not absolutely reliable, so parameter verification can be seen everywhere. Parameter verification in different scenarios is necessary, but its fundamental purpose is to give prompt information to the requester, interrupt the process quickly and respond quickly.

1. Reference

Many encapsulation ideas, design patterns, or parameter verification mentioned here can refer to the existing Java source code or excellent framework, which is a basic consciousness that should be possessed.

Java native method java.lang.Thread Threads:


public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();
    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();   
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}

In the Java source code, most of them use the native if judgment mode to check the parameters

Spring Framework org.springframework.util.ClassUtils Tool class part code:


public static Class<?> forName(String name, @Nullable ClassLoader classLoader)
			throws ClassNotFoundException, LinkageError {
		Assert.notNull(name, "Name must not be null");
		Class<?> clazz = resolvePrimitiveClassName(name);
		if (clazz == null) {
			clazz = commonClassCache.get(name);
		}
		if (clazz != null) {
			return clazz;
		}
}

In addition to the basic if judgment, the Spring framework also encapsulates 1 org.springframework.util.Assert Assertion tool class.

2. Common verification methods

If judgment


@GetMapping("/check/base")
public String baseCheck (@RequestParam("var") String var){
    if (var == null) {
        return var+" is null" ;
    }
    if ("".equals(var)){
        return var+" is empty" ;
    }
    if ("hello".equals(var)){
        return var+" sensitive word " ;
    }
    return var + " through " ;
}

This kind of judgment is very common in the code, but the main object that encounters verification is very large, and if if judgment needs to be written repeatedly in a distributed environment, error-prone is one aspect, and patience test for developers is another aspect.

Valid Component

In the early years, the popular common verification components Hibernate-Validator , which arose later Validation-Api It is said to be implemented with reference to the former, but this is not important. Both of them simplify the verification mechanism for JavaBean.

Based on the annotation, the field attribute of the Java object is marked, and the prompt information if the verification fails is set.


public class JavaValid {

    @NotNull(message="ID Cannot be empty ")
    private Integer id ;

    @Email(message=" Mailbox format exception ")
    private String email ;

    @NotEmpty(message = " Field cannot be empty ")
    @Size(min = 2,max = 10,message = " Unreasonable field length ")
    private String data ;
}

Verification result printing:


@GetMapping("/param/multi")
public String paramMulti (@RequestParam("key") String key, @RequestParam("var") String var){
    return "Resp:"+key+var ;
}
0

Interface uses:


@GetMapping("/param/multi")
public String paramMulti (@RequestParam("key") String key, @RequestParam("var") String var){
    return "Resp:"+key+var ;
}
1

This verification mechanism is based on annotation, which can greatly simplify the common parameter entry verification, but it is not suitable for the legal verification of business parameters, such as the absence of common ID and state interception.

Assert Assertion

As for the Assert assertion mode, it was common in unit testing at first, and then it became common in various excellent frameworks, such as Spring, Mybatis, etc., and then began to appear in business code:


@GetMapping("/param/multi")
public String paramMulti (@RequestParam("key") String key, @RequestParam("var") String var){
    return "Resp:"+key+var ;
}
2

Assert assertion can replace the traditional if judgment, greatly reduce the number of lines of code for parameter verification, and improve the readability of the program. This style is a popular way at present.

5. Source code address

GitHub・地址https://github.com/cicadasmile/middle-ware-parentGitEE

地址https://gitee.com/cicadasmile/middle-ware-parent

The above is the SpringBoot2 parameter management practice, and the details of participating in the verification are included. For more information about SpringBoot2 parameter verification, please pay attention to other related articles on this site!


Related articles: