因此,我决定开始使用 Undertow,这既是一项实验,也是因为它在基准测试中取得了出色的成绩。虽然我认为它很棒,但有一项功能要么缺失要么我找不到。
我想开发一个 RESTful 网络服务,因此识别正在调用的 HTTP 方法对我来说很重要。现在我可以从 HttpServerExchange 参数中的 RequestMethod 获取它,但如果必须对每个处理程序都这样做,那将变得乏味。
我的解决方案有效但我知道是错误的,是这样的:
创建了一个名为 HTTPMethod 的注解接口(interface):
@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)在上述情况下正确使用注解的正确方法是什么?
最佳答案
在 Redhat 团队和 Undertow 贡献者的帮助下设法找到了几个答案,希望这对其他人有帮助:
1) 最新版本的 Undertow 有一个 io.undertow.server.RoutingHandler与我建议的完全相同的类,只是不需要注释。
2) JBoss 有一个用于 RESTEasy 的适配器:resteasy-undertow或自定义框架 hammock其中包括 RESTEasy + Undertow + Weld。
3) Undertow 已经支持 Servlets 3,因此如果您愿意,可以将它们结合使用注释。
关于java - 我如何处理 Undertow 中的 HTTP 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003216/