我正在寻找一个很好的模式,为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的最佳实践是什么?
我的想法:
我想出了一个概念:
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,但是它失败了(例如,在resteasy尝试在部署时使用它之后加载bean )。
有什么想法--有什么好的验证模式吗?或者是否有可能让我的概念发挥作用?
编辑:,还是,哪个是最好的,在Resteasy中有一些过滤器对应的?在实际实现之前调用我的方法(筛选器),但参数(arg1、arg2)已经解析过的方案?
事先谢谢,很抱歉写了很长的一篇文章;
发布于 2012-02-23 06:32:16
(1)最干净的方法可能是使用JavaEE6Bean验证框架。这需要编写自定义验证拦截器。在这种情况下,您必须更改您的方法,所以,而不是
public Response doSomething ( String arg1, Integer arg2 )
您将使用域对象作为参数。
public Response doSomething ( JAXBElement<MyDomainObject> myOJaxb )
然后,您需要转换请求,以便它们提供XML或JSON格式的数据,这些数据可以自动转换为实际对象。
(2)另一种选择是使用正常的ServletFilter。
(3)准备自定义注释a‘’la验证,然后需要插入自定义注释处理器(查看Lombok项目,作为一个灵感)。
(4)最简单的解决方案是使用内置的REST验证。
@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")
但这适用于路径参数,而不是查询参数(我认为,但没有检查JAX-RS规范)。
您的选择取决于您对接口有多大的灵活性,以及您有多少时间。
如果您想出一个通用的、可插入的Resteasy解决方案,类似于选项(3)中的建议,并在GitHub上开放源代码,那么很多人都会喜欢你的:)
https://stackoverflow.com/questions/6226747
复制