Spring IP Address Checker

I am looking for an opportunity to check IP addresses in my Spring roo project.

My essence looks like this

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

      

With this setting, it is only checked if the string is 7 to 15 characters long, but it is not really an IP address.

Something like

@validIpAddress
private String ip;

      

it would be nice.

Any idea if this is possible?

+3


source to share


3 answers


Definitely possible. You will need to code your custom annotation and implementation class. Not too much effort. See here for a background: 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 {};
}

      



and

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

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

      

+6


source


You can use JSR 303 validation pattern with 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;

      



edit: escape backslash

+7


source


Essentially, you want to use JSR-303 annotations with a custom validator. See a complete working example here .

0


source







All Articles