我尝试为我的Apache tomee webapps创建一个JAXRS ContainerResponseFilter。
首先是我的pom.xml
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0-6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
...
<plugin>
<groupId>org.apache.openejb.maven</groupId>
<artifactId>tomee-maven-plugin</artifactId>
<configuration>
<context>ROOT</context>
<libs>
<lib>javax.ws.rs:javax.ws.rs-api:2.0.1</lib>
<lib>javax.annotation:javax.annotation-api:1.2</lib>
</libs>
<tomeeClassifier>jaxrs</tomeeClassifier>
</configuration>
</plugin>
我的界面:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@NameBinding
public @interface CrossDomain {}
我的过滤器实现:
@Provider
@Priority(Priorities.AUTHENTICATION)
@CrossDomain
public class CrossDomainProvider implements ContainerResponseFilter
{
@Override
public void filter(ContainerRequestContext creq, ContainerResponseContext cres) throws IOException
{
final Logger Log = LoggerFactory.getLogger(CrossDomainProvider.class);
Log.debug("FILTER CROSS ! ");
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}
}
我的休息服务:
@Path("/groups")
@CrossDomain
public class GroupRestService
{
@EJB
private GroupService groupService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Group> getAllGroups()
{
return groupService.findAllGroups();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Group getGroupById(@PathParam("id")String id)
{
return groupService.findGroupById(id);
}
}
我的项目编译得很好,我甚至可以使用localhost主机访问我的web服务,但它永远不会进入我的过滤器,如果我尝试使用外部主机,那么它不起作用。我永远不会看到我的登录控制台。