java Spring IP地址验证

nfg76nw0  于 2023-06-20  发布在  Java
关注(0)|答案(4)|浏览(187)

我正在寻找一种可能性来验证我的Spring Roo项目中的IP地址。
我的实体看起来像这样

package com.ip.test.domain;

import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class IP {

@NotNull
@Size(min = 7, max = 15)
private String ip;

@ManyToOne
private Hoster Hoster;
}

使用这种设置,它只验证字符串是否包含7到15个字符,而不是IP地址。
就像

@validIpAddress
private String ip;

会很好
有没有可能?

2vuwiymt

2vuwiymt1#

您可以使用JSR 303模式验证器,使用IP地址regex:

@NotNull
@Pattern(regexp = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")
private String ip;

编辑:转义反斜杠

lsmepo6l

lsmepo6l2#

绝对有可能。您需要编写一个自定义注解和实现类。不用太费力。请参阅此处了解背景:http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#validator-customconstraints

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Documented
@Constraint(validatedBy = IpAddressValidator.class)
public @interface IpAddress
{
  String message() default "{ipAddress.invalid}";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}

和/或

public class IpAddressValidator implements ConstraintValidator<IpAddress, Object>
{
  @Override
  public void initialize(IpAddress constraintAnnotation)
  {
  }

  @Override
  public boolean isValid(Object value, ConstraintValidatorContext cvContext)
  {
    // logic here
  }
}
lnvxswe2

lnvxswe23#

实际上,您希望使用带有自定义验证器的JSR-303注解。参见完整的工作示例here

uklbhaso

uklbhaso4#

我知道我在挖掘一个旧的答案,但我想在这里添加一些东西。我认为这可能会有所帮助,因为我个人对所有这些答案都不满意,有几个原因。
1).像这样在每个IP上面做一个@Pattern有点难看,如果能包含一个快速的类就很酷了。
2). IPv4很简单。IPv6不是。
如果你想使用IPv6,请阅读以下内容:Regular expression that matches valid IPv6 addresses
3).如果你想要一个简单的IPv4验证器在一个很好的类,看看这个代码,我砍在一起,并在我自己的网站上测试。效果很好。

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Pattern(regexp = ValidIPv4.IPV4_REGEX)
@Constraint(validatedBy = {})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidIPv4 {
    // JSR 303 Pattern Validator for IPv4
    String IPV4_REGEX = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

    String message() default "must match " + IPV4_REGEX;

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

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

当然,还有一个非常好的单元测试,你可以用途:

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.validation.annotation.Validated;
import org.testng.annotations.Test;

import java.util.Set;

import static org.testng.AssertJUnit.assertEquals;

public class ValidIPv4Test {

    @Validated
    private class MyClass {
        @ValidIPv4
        private String ipv4;

        public String getIpv4() {
            return ipv4;
        }

        public void setIpv4(String ipv4) {
            this.ipv4 = ipv4;
        }
    }

    @Test
    public void testValidFormat() {
        // Create a ValidatorFactory and Validator
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        // Create an object with the field to validate
        MyClass myClass = new MyClass();
        myClass.setIpv4("127.0.0.1");

        // Perform validation
        Set<ConstraintViolation<MyClass>> violations = validator.validate(myClass);

        // Assert that there are no validation violations
        assertEquals(0, violations.size());
    }

    @Test
    public void testInvalidFormat() {
        // Create a ValidatorFactory and Validator
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        // Create an object with the field to validate
        MyClass myClass = new MyClass();
        myClass.setIpv4("827.0.0.1");

        // Perform validation
        Set<ConstraintViolation<MyClass>> violations = validator.validate(myClass);

        // Assert that there is one validation violation
        assertEquals(1, violations.size());

        // Assert that the violation is related to the field
        ConstraintViolation<MyClass> violation = violations.iterator().next();
        assertEquals("must match \"" + ValidIPv4.IPV4_REGEX + "\"", violation.getMessage());
        assertEquals("ipv4", violation.getPropertyPath().toString());
    }
}

相关问题