所以我决定开始使用Undertow,既是一个实验,也是由于它在基准测试中取得的巨大成果。虽然我认为这太棒了,但有一项功能可能会丢失或找不到。如何处理Undertow中的HTTP方法?
我想开发一个RESTful Web服务,所以对于识别哪个HTTP方法被调用很重要。现在我可以从HttpServerExchange参数中的RequestMethod中获得这个信息,但是如果每个处理程序都会变得单调乏味的话。
我的解决办法,这工作,但我知道错了,是这样的:
创建注释界面称为列举HTTPMethod:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HTTPMethod {
public enum Method {
OTHER, GET, PUT, POST, DELETE
}
Method method() default Method.OTHER;
“抽象” 类(不是抽象的):
public abstract class RESTfulHandler implements HttpHandler {
@Override
public void handleRequest(HttpServerExchange hse) throws Exception {
for (Method method : this.getClass().getDeclaredMethods()) {
// if method is annotated with @Test
if (method.isAnnotationPresent(HTTPMethod.class)) {
Annotation annotation = method.getAnnotation(HTTPMethod.class);
HTTPMethod test = (HTTPMethod) annotation;
switch (test.method()) {
case PUT:
if (hse.getRequestMethod().toString().equals("PUT")) {
method.invoke(this);
}
break;
case POST:
if (hse.getRequestMethod().toString().equals("POST")) {
method.invoke(this);
}
break;
case GET:
if (hse.getRequestMethod().toString().equals("GET")) {
method.invoke(this);
}
break;
case DELETE:
if (hse.getRequestMethod().toString().equals("DELETE")) {
method.invoke(this);
}
break;
case OTHER:
if (hse.getRequestMethod().toString().equals("OTHER")) {
method.invoke(this);
}
break;
}
if (test.method() == HTTPMethod.Method.PUT) {
method.invoke(this);
}
}
}
}
}
和上述两者的实施方案:
public class ItemHandler extends RESTfulHandler{
@HTTPMethod(method=GET)
public List<String> getAllItems()
{
System.out.println("GET");
return new ArrayList<>();
}
@HTTPMethod(method=POST)
public void addItem()
{
System.out.println("POST");
}
@HTTPMethod
public void doNothing()
{
System.out.println("OTHERS");
}
}
现在,正如我所说,它的工作原理,但我敢肯定的是,抽象类和它的实现有一些缺失,使他们正确地胶。所以我的问题有两个:
1)是否有更好/适当的方式来过滤Undertow中的HTTP请求? 2)在上述情况下正确使用注释的正确方法是什么?