The previous chapters have realized the data addition, deletion, checking and modification in RMS system and batch import through Excel. However, there are still some remaining problems, for example, when adding or editing, we can input negative values of monster health, armor and other data, which is unreasonable and meaningless. In this chapter, we will realize the verification of server parameters.

Add dependencies

In the POM.xml of the RMS module, add a validation component dependency (note: we refer to the latest version of the previous component. The latest version of hibernate-Validator, 6.xx+, contains el-api.jar, which is not compatible with maven.

<!-- 参数校验 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.1.Final</version>
</dependency>
Copy the code

The component itself provides some annotations, @notnull, @notblank, @min, etc., to validate the model, but the error message is not good enough. The default universal error message does not make it clear which field is reporting the error. It would be tedious to add a prompt for each field, so we’ll make a little change here and use the util module to create a generic validation kit.

Add a dependency to the util module’s pom.xml:

< the dependency > < groupId > javax.mail. Validation < / groupId > < artifactId > validation - API < / artifactId > < version > 2.0.1. The Final < / version > <scope>provided</scope> </dependency>Copy the code

2. Add custom notes and prompts

Not empty check, for example, the new package in the util module. Com idlewow. Util. Validation. Annotaion, under this package to create a new annotation class NotBlank. Java is as follows:

package com.idlewow.util.validation.annotation;


import com.idlewow.util.validation.validator.NotBlankValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@Constraint(validatedBy = NotBlankValidator.class)
@NotNull
public @interface NotBlank {
    String field() default "";

    String message() default "{field.not.blank.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        NotBlank[] value();
    }
}
Copy the code

Annotations with, also needs a corresponding checker, new package com. Idlewow. Util. Validation. The validator, and new type NotBlankValidator under this package is as follows:

package com.idlewow.util.validation.validator; import com.idlewow.util.validation.annotation.NotBlank; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class NotBlankValidator implements ConstraintValidator<NotBlank, CharSequence> { public NotBlankValidator() { } public void initialize(NotBlank annotation) { } @Override public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) { if (charSequence == null) { return false; } else { return charSequence.toString().trim().length() > 0; }}}Copy the code

In addition, when verifying the model, different scenarios have different requirements. For example, the primary key is added by the database, so there is no need to add the primary key. When editing, the primary key ID must be specified for non-null verification. . Therefore, we in the com idlewow. Util. Validation packet in a new class of check group ValidateGroup:

package com.idlewow.util.validation; import javax.validation.groups.Default; import java.io.Serializable; public class ValidateGroup implements Serializable { public interface Create extends Default { } public interface Update  extends Default { } }Copy the code

Finally, we add util module on the resource resource directory message resource file ValidationMessages. Properties,

Null. Message ={field} cannot be null Field. Min. message={field} must not be smaller than {value} field.max. Message ={field} must not be larger than {value} Field.range. message={field} must be between {min} and {Max}. Field.positive. Message ={field} must be positiveCopy the code

Three, the use of parameter verification annotations

First, we need to annotate the model we need to verify. Here’s the monster model:

package com.idlewow.mob.model; import com.idlewow.common.model.BaseModel; import com.idlewow.util.validation.annotation.NotBlank; import com.idlewow.util.validation.annotation.NotNull; import com.idlewow.util.validation.annotation.Positive; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; @Data @EqualsAndHashCode(callSuper = true) public class MapMob extends BaseModel implements Serializable { @ NotBlank (field = "primary key id", groups = ValidateGroup. Update. The class) private String id; @notBlank (field = "monster name ") private String name; @notblank (field = "mapId ") private String mapId; @notBlank (field = "mapName ") private String mapName; @notnull (field = "faction ") private Integer faction; @notnull (field = "monster ") private Integer mobClass; @notnull (field = "monster type ") private Integer mobType; @positive (field = "level ") private Integer level; @positive (field = "life ") private Integer HP; @positive (field = "damage ") private Integer damage; @positive (field = "Positive ") private Integer amour; }Copy the code

Once the model annotations are added, we add a generic validation method to BaseController that can be called from controllers:

public abstract class BaseController { ...... . @Autowired protected Validator validator; . . protected CommonResult validate(Object object, Class... classes) { Set<ConstraintViolation<Object>> set = validator.validate(object, classes); if (set ! = null && set.size() > 0) { ConstraintViolation constraintViolation = set.iterator().next(); return CommonResult.fail(constraintViolation.getMessage()); } return CommonResult.success(); }}Copy the code

In MapMobController add and edit methods, add validation logic,

@controller @requestMapping ("/manage/map_mob") public class MapMobController extends BaseController {...... ... @ResponseBody @RequestMapping(value = "/add", method = RequestMethod.POST) public Object add(@RequestBody MapMob mapMob) { try { CommonResult commonResult = this.validate(mapMob, ValidateGroup.Create.class); if (! commonResult.isSuccess()) return commonResult; mapMob.setCreateUser(this.currentUserName()); mapMobManager.insert(mapMob); return CommonResult.success(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); return CommonResult.fail(); }}... ... @ResponseBody @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public Object edit(@PathVariable String id, @RequestBody MapMob mapMob) { try { if (! Id. Equals (mapMob.getid ())) {return commonResult.fail ("id not consistent "); } CommonResult commonResult = this.validate(mapMob, ValidateGroup.Update.class); if (! commonResult.isSuccess()) return commonResult; mapMob.setUpdateUser(this.currentUserName()); mapMobManager.update(mapMob); return CommonResult.success(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); return CommonResult.fail(); }}}Copy the code

Four, the operation effect

  

summary

This chapter realizes the background verification of the request parameters. Of course, it can also be verified in advance at the front end, but the verification at the back end is generally essential.

The source code download address: idlestudio.ctfile.com/fs/14960372…

In this paper, the original address: www.cnblogs.com/lyosaki88/p…

Project Exchange Group: 329989095