使用 java EE 6 注释进行 Servlet 过滤? [英] Servlet Filtering using java EE 6 annotation?

查看:34
本文介绍了使用 java EE 6 注释进行 Servlet 过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 EE 6 中使用 @ApplicationPath 和 @Path 注释来模拟 servlet 过滤器链?

Is it possible to simulate a servlet filter chain using @ApplicationPath and @Path annotations in EE 6?

示例:

@ApplicationPath("/api")
class Filter extends Application { 
    @Path("/*")
    public void filter() {
        log.info("Request to API");
    }
}

...

@Path("/foo")
class Foo {
    @GET
    @Path("/bar")
    @Produces("text/plain")
    public String bar() {
        return "Hello World";
    }
}

URL 将是 http://foobar.com/api/foo/bar 但过滤器"方法将被调用,就好像它是一个 servlet 过滤器链.我知道上面的方法行不通,但是在这个同类中是否有一种带注释的方法可以实现与从 web.xml 文件配置过滤器"相同的效果?

Where the URL would be http://foobar.com/api/foo/bar but the "filter" method would be invoked as if it were a servlet filter chain. I know the approach above wont work but is there an annotated approach in this ilk that would achieve the same as if the "Filter" was configured from web.xml file?

推荐答案

JBoss 7(甚至 JBoss 6 已经)支持 Java EE 6,而后者又涵盖了 Servlet 3.0.也许您的 web.xml 被错误地声明为符合 Servlet 2.5,导致 @WebFilter 根本无法工作.确保您的 web.xml 的根声明被声明为符合 Servlet 3.0,如下所示:

JBoss 7 (even JBoss 6 already) supports Java EE 6 which in turn covers Servlet 3.0. Perhaps your web.xml is incorrectly been declared conform Servlet 2.5 which caused the @WebFilter not to work at all. Ensure that the root declaration of your web.xml is been declared conform Servlet 3.0 like follows:

<web-app 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

然后你就可以使用 @WebFilter:

Then you can just use @WebFilter:

@WebFilter("/api/*")
public class FooFilter implements Filter {

    // ...

}

顺便说一下,您在此处展示的示例是 JAX-RS 的一部分,它是构建在 Servlet 之上的另一个 API(RESTful Web 服务 API).要了解有关 JAX-RS 的更多信息,请参阅 Jersey 用户指南有用.

The examples which you've shown there are by the way part of JAX-RS, which is another API (a RESTful webservice API) built on top of Servlets. To learn more about JAX-RS, the Jersey user guide may be useful.

这篇关于使用 java EE 6 注释进行 Servlet 过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆