我可以为Resteasy服务提供自定义输入验证的好模式。
假设我有这个服务:
@Local
@Path("/example")
public interface IExample {
public Response doSomething ( @QueryParam("arg1") String arg1, @QueryParam("arg2") Integer arg2);
}
我已经实现的功能:
@Stateless
public class Example implements IExample {
@Override
public Response doSomething ( String arg1, Integer arg2 ) { ... }
}
如何验证arg1和arg2是最佳实践?
我的想法:
- 在doSomething(...)方法内部进行验证。缺点是:当我在未来添加一些参数(例如arg3)时,我很容易忘记验证它。
- 使用自定义的javax.servlet.Filter进行验证。缺点是:由于Resteasy框架尚未解析arg1和arg2,因此我无法在过滤器中访问它们。
我提出了这个概念:
public class ExampleValidator implements IExample {
public static class ValidationError extends RuntimeException { ... }
@Override
public Response doSomething ( String arg1, Integer arg2 ) {
// here do validation. In case of failure, throw ValidationError
return null;
}
}
可以按照以下方式使用:
@Stateless
public class Example implements IExample {
@Override
public Response doSomething ( String arg1, Integer arg2 ) {
try {
(new ExampleValidator()).doSomething(arg1, arg2);
} catch ( ValidationError e ) {
// return Response with 400
}
}
}
那么,当我更改IExample.doSomething方法签名时,由于编译时错误,我必须更新Validator。为了让Resteasy不将ExampleValidator解释为服务,我使用了resteasy.jndi.resources而不是resteasy.scan,但它失败了(Example bean在部署时尝试使用它之后才被加载)。
有什么好的验证模式吗?或者有没有可能以某种方式使我的概念工作?
编辑:或者,最好的方法是,在Resteasy中是否有一些过滤器对应项?一些方案,通过该方案,我的方法(过滤器)将在实际实现之前调用,但参数(arg1、arg2)已经被解析?
提前感谢,抱歉发帖太长;) 卡米尔