开发者

Best ways of performing server side validations on data using Java

开发者 https://www.devze.com 2023-02-19 11:53 出处:网络
Could someone guide me on this fundamental question: What are the best way ways of performing server side validations on data using Java?

Could someone guide me on this fundamental question: What are the best way ways of performing server side validations on data using Java?

I would like 开发者_JS百科to know if there are open source libraries available to perform server side validations as well.

Any help is appreciated.


It depends on which web developement framework you are using.


Raw JSP Servlet

If you are using simple jsp servlet, Then I would suggest add one validator package/jar for each form/jsp screen. and validate it from controller before passing to service.


JSF

If you are using JSF then there is very well designed validation phase provided , You can use ready made validators (you can just add annotation on the form field and its done) or you can create your own validators also.


Spring MVC

If you are using Spring MVC , it has also got a saperate layer for validation.


Struts

Struts has also got saperate layer for validation


If you are looking to validate POJOs, you can have a look at the Oval framework http://oval.sourceforge.net/

JSR-303 (and its implementations) may also help if ur app is designed based on pojos or beans

Here is a sample custom validation in OVal: Lets say you have to validate variables map in SomeValueClass and ensure the value of key 'greeting' is always present.

public class SomeValueClass {

@FormCollection
Map variables;


public static void main(String[] args) {
    SomeValueClass svc1 = new SomeValueClass();
    svc1.variables = new HashMap();
    svc1.variables.put("greeting", "");

    Validator validator = new Validator();
    List<ConstraintViolation> violations = validator.validate(svc1);
    System.out.println("svc1 violations.size() = " + violations.size());
}

The @FormCollection annotation on "Map variables;" is a custom validator and is as below:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@net.sf.oval.configuration.annotation.Constraint(checkWith = FormCollectionCheck.class)
public @interface FormCollection {
  String message() default "Some errors in the form";
}

And the constraint check class will look like this:

public class FormCollectionCheck extends AbstractAnnotationCheck<FormCollection> {
  public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context, Validator validator) {
    Map vars = (Map) valueToValidate;
    return !(vars.get("greeting")==null || ((String)vars.get("greeting")).length()<=0);
  }
}

Hope that helps, Cheers


then you go for the framework which are providing inbuilt validations like struts etc. Those will provide you validation component. Also its an opensource.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号