简体   繁体   中英

Servlet Filtering using java EE 6 annotation?

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

Example:

@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";
    }
}

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 (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">

Then you can just use @WebFilter :

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

    // ...

}

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.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM