filter映射中的无效

我有一个@POSTrest方法,我想为它做过滤,所以只有登录在应用程序中的人才能访问它。 这是我的@POST方法:

@POST @Path("/buy") public Response buyTicket(@QueryParam("projectionId") String projectionId, @QueryParam("place") String place){ Projection projection = projectionDAO.findById(Long.parseLong(projectionId)); if(projection != null){ System.out.println(projection.getMovieTitle()); System.out.println(place); projectionDAO.buyTicket(projection, userContext.getCurrentUser(), place); } return Response.noContent().build(); } 

这是我为这种方法编写的filter:

 @WebFilter("rest/projection/buy") public class ProtectedBuyFunction implements Filter { @Inject UserContext userContext; public void init(FilterConfig fConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isHttpCall(request, response)) { return; } HttpServletResponse httpServletResponse = (HttpServletResponse) response; HttpServletRequest httpServletRequest = (HttpServletRequest) request; User currentUser = userContext.getCurrentUser(); if (currentUser == null) { String loginUrl = httpServletRequest.getContextPath() + "/login.html"; httpServletResponse.sendRedirect(loginUrl); return; } chain.doFilter(request, response); } private boolean isHttpCall(ServletRequest request, ServletResponse response) { return (request instanceof HttpServletRequest) && (response instanceof HttpServletResponse); } public void destroy() { }} 

问题是我总是得到一个exception并且服务器拒绝启动,例外是:

 Invalid  rest/projection/buy in filter mapping 

我正在使用带有Jax-RS的TomEE服务器。 有什么办法可以解决这个问题吗?

根据servlet规范的映射路径应遵循以下规则:

  • 目录映射:以“/”字符开头并以“/ *”后缀结尾的字符串用于路径映射。
  • 扩展映射:以“*”开头的字符串。 prefix用作扩展映射。
  • Context Root:空字符串(“”)是一个特殊的URL模式,它完全映射到应用程序的上下文根,即http:// host:port / /forms的请求。 在这种情况下,路径信息是’/’,servlet路径和上下文路径是空字符串(“”)。
  • 默认Servlet:仅包含’/’字符的字符串表示应用程序的“默认”servlet。 在这种情况下,servlet路径是请求URI减去上下文路径,路径信息为null。
  • 精确映射:所有其他字符串仅用于完全匹配。

在您的情况下,它不以“/”开头。 如果使用servletfilter,则应该具有上下文根的绝对URL。 在开头添加“/”。 它应该工作。

最简单的方法是使用JAX-RSfilter而不是Servletfilter。 你可以在这里找到它们的文档: https : //jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9580

对于Servletfilter,请发布您的servlet上下文以及JAX-RS资源的映射,以便找出出现错误的原因。