目前,我正在根据用户输入生成许可证密钥,并将其传递给我的Java代码。生成密钥的代码是:

@PostMapping("/generate")
    public License generateLicense(@RequestBody License lic) {

        SecurityHashService service = new SecurityHashService();
        StringBuffer combinedKey = new StringBuffer();

        combinedKey.append("hardwareKey:").append(lic.getHardwareKey()).append(",").append("customerId:").append(lic.getCustomerId()).append(",")
        .append("product:").append(lic.getProduct()).append(",").append("msan:").append(lic.getMsan()).append(",")
        .append("msan:").append(lic.getCpe()).append(",")
        .append("connections:").append(lic.getConnections()).append(",").append("concurrent:").append(lic.getConcurrent()).append(",")
        .append("zmsVersion:").append(lic.getZmsVersion()).append(",").append("expiryDate:").append(lic.getExpiryDate().getTime());

        final String encryptedkey = service.generateKey(combinedKey.toString(), lic.getHardwareKey());
        lic.setLicenseKey(encryptedkey);
        return licenseDao.saveLicense(lic);
    }


License类指定所有参数:
@实体
@Table(name =“许可证”)
@EntityListeners(AuditingEntityListener.class)

public class License {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @NotBlank
    private String product;

    @NotBlank
    private String hardwareKey;

    @NotBlank
    private String licenseKey;

    @NotNull
    private Date expiryDate;

    @NotNull
    private Integer concurrent;

    @NotNull
    private Integer connections;

    @NotNull
    private Integer msan;

    @NotNull
    private Integer cpe;

    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date creationDate;

    @NotNull
    private String customerId;

    @NotNull
    private String zmsVersion;


在“角度”部分:它获取所有值并生成许可证。组成部分是:

export class GeneratelicenseComponent implements OnInit {
  editable: boolean = false;
  licenseKey: string = "";
  submitted: boolean = false;
  form: FormGroup;
  minDate = new Date();
  allProducts:any=[];
  products: any=[];
  constructor(
    private generateLicenseService: GeneratelicenseService,
    private builder: FormBuilder, public dialog: MatDialog) { }

  ngOnInit() {
    this.createForm();
    this.generateLicenseService.getProducts()
    .subscribe((data) => {
      console.log(data)
      this.allProducts = data;
      this.allProducts.forEach(element => {
        this.products.push({
          "value" : element["productId"],
          "viewValue" : element["productId"]
        })

      });
    });
    this.getDefaultConfig();
  }

  createForm() {
    this.form = this.builder.group({
        hardwareKey: ['', Validators.required],
        customerID: ['', Validators.required],
        product: ['', Validators.required],
        zmsVersion: ['', Validators.required],
        expiryDate: ['', Validators.required],
        concurrent: ['', Validators.required],
        connections: ['', Validators.required],
        msan: ['', Validators.required],
        cpe: ['', Validators.required]
    });



  }

  zmsVersions = [
    { value: '03.00.00', viewValue: '03.00.00' },
    { value: '03.01.00', viewValue: '03.01.00' },
    { value: '03.02.00', viewValue: '03.02.00' },
    { value: '03.03.00', viewValue: '03.03.00' },
    { value: '03.03.20', viewValue: '03.03.20' },
    { value: '03.04.00', viewValue: '03.04.00' }
  ]

  getDefaultValues() {
    let product = this.form.get('product').value;
    if(product=="MXK"){
      const dialogRef = this.dialog.open(GenerateMxkLicenseDialog, {
       width: '450px',
       disableClose: true,
       autoFocus: true
     });
    }

    if(product="OSSXML"){
      debugger
      this.form.get('customerID').disable();
      this.form.get('zmsVersion').disable();
      this.form.get('concurrent').disable();
      this.form.get('connections').disable();
      this.form.get('msan').disable();
      this.form.get('cpe').disable();
    }
    if (product !=null) {
      //if (product == 'ZMS-VA' || product == 'ZMS-TIER 1' || product == 'ZMS-TIER 2' || product == 'ZMS-TIER 3') {
        let defaultArray = this.getDefaultConfig().filter((item) => {
        return item.id === product;
        });
        debugger
        this.form.get('concurrent').setValue(defaultArray[0].concurrent)
        this.form.get('connections').setValue(defaultArray[0].connections)
        this.form.get('msan').setValue(defaultArray[0].msan);
        this.form.get('cpe').setValue(defaultArray[0].cpe);
        this.form.get('expiryDate').setValue('');
      } else {
      debugger
      this.form.get('concurrent').setValue('')
      this.form.get('connections').setValue('')
      this.form.get('msan').setValue('')
      this.form.get('cpe').setValue('');
      var targetDate = new Date();
      targetDate.setDate(targetDate.getDate() + 365);
      this.form.get('expiryDate').setValue(targetDate);
    }
}

  getDefaultConfig() {

    let defaultProductConfig: any=[];
    this.allProducts.forEach(element => {

      defaultProductConfig.push
        ({"id": element["productId"],
        "concurrent" : element["defaultConcurrent"],
        "connections": element["defaultConnections"],
        "msan": element["msan"],
        "cpe": element["cpe"]});
    });
    console.log("----->"+JSON.stringify(defaultProductConfig));
    return defaultProductConfig;
  }

  onSubmit() {
    console.log(this.allProducts[0]);
    this.submitted = true;
    if (this.form.invalid) {
      return;
    }
    let product = this.form.value.product;
    let hardwareKey = this.form.value.hardwareKey;
    let zmsVersion = this.form.value.zmsVersion;
    let customerID = this.form.value.customerID;
    let concurrent = this.form.value.concurrent;
    let connections = this.form.value.connections;
    let expiryDate = this.form.value.expiryDate;
    let msan =  this.form.value.msan;
    let cpe =  this.form.value.cpe;

    console.log("hardwareKey=====> "+hardwareKey);

    let licenseValuesArr = [
      {
        "hardwareKey" : hardwareKey,
        "product" : product,
        "zmsVersion" : zmsVersion,
        "customerId" : customerID,
        "concurrent" : concurrent,
        "connections" : connections,
        "expiryDate" : expiryDate,
        "msan" : msan,
        "cpe" : cpe
      }
    ];


    this.generateLicenseService.generateLicense(licenseValuesArr)
      .subscribe((data) => {
        debugger
        console.log(data["licenseKey"])
        this.licenseKey = data["licenseKey"];
      },
      error => {
        console.log(error)
      });
  }


在表单中,我有一个产品字段,这是一个下拉列表。



<td colspan="2" width="100%">
                        <mat-form-field class="generate-full-width">
                            <mat-select placeholder="Product" formControlName="product" name="product" (selectionChange)="getDefaultValues()">
                                <mat-option *ngFor="let product of products" [value]="product.value">
                                    {{product.viewValue}}
                                </mat-option>
                            </mat-select>
                            <mat-error *ngIf="submitted && hasError('product', 'required')">Product is required</mat-error>





现在,假设产品名称为“ OSSXML”,那么我想禁用除“硬件密钥”和“到期日期”之外的所有输入表单字段。我不想通过弹出窗口而不是单独的按钮来为此生成许可证来执行此操作。我试图禁用这些字段,将值设置为“”,并应用了多个if-else条件,但是每次它检查其他值时,在我的应用程序中,都会出现错误:

List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=connections, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=cpe, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=zmsVersion, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=msan, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=concurrent, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=customerId, rootBeanClass=class com.licensegeneration.licenseGenerator.model.License, messageTemplate='{javax.validation.constraints.NotNull.message}'}


请建议我该怎么做。我希望避免在应用程序中添加新类或创建单独的服务。另外,由于生成的许可证存储在称为许可证的表中,因此是否需要更改此代码。我想将OSSXML的许可证存储在同一表中。

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/licenseGenerator")
public class LicenseController {

最佳答案

出现此错误的原因是,您已在实体类中用@NotBlank注释了这些字段-这意味着JPA不会让您使用这些包含null的字段来保存新实体。

您可以做的是从某些情况下为空的字段中删除@NotBlank
或者,如果不能删除注释,则可以确保角度应用程序将发送{"connections": ""}而不是{"connections": null}
为此,如果选择的产品是OSSXML,则可以使用patchValue方法用""填充字段,如下所示:

this.form.patchValue({
  connections: "",
  cpe: "",
  zmsVersion: "",
  msan: "",
  concurrent: "",
  customerId: ""
});


如果要指定其他字段,请使用在createForm()方法中使用的值

在检查表单是否有效之后,在onSubmit()方法中调用它。

08-28 15:37