0

im new to Java and Spring. Im doing my first app with Spring MVC Begginers Guide and i have problem with my "category" field validator. It doesnt work correctly.. Tbh It doesn't work at all.

category.java

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CategoryValidator.class)
@Documented
public @interface Category {
    String message() default "{com.packt.webstore.validator.Category.message}";
    Class<?>[] groups() default {};
    public abstract Class<? extends Payload>[] payload() default {};
    String[] allowedCategories() default {"Laptop","Tablet","Smartfon"};
}

CategoryValidator.java

public class CategoryValidator implements ConstraintValidator<Category, String> {
String[] allowedCategories;
public void initialize( Category constraintAnnotation ) {
    this.allowedCategories = constraintAnnotation.allowedCategories();
}
public boolean isValid( String value, ConstraintValidatorContext context ) {
    for( String category : allowedCategories ) {
        if( value == category ) {
            return false;
        }
    }
    return true;
}

The problem is that everything i type in my "category" field it return that its not correct category :/

I was googling about my problem but didnt find anything :( Can somebody explain me what am I doing wrong :)? Thanks!

crooked
  • 675
  • 2
  • 11
  • 22

1 Answers1

0

This answer should be in a the comment section but i cannot yet post a comment :

String equality does not work with == operateur.

You must use String.equals(String anotherString) to compare them.

Using ==, you only verify if the two strings are the same in memory. Equals compare the value of the String.

Hope it's helps