过滤器映射中的<url-pattern>无效

时间:2015-06-27 14:19:25

标签: java java-ee servlets filter mapping

我有一个@POST rest方法,我想为它做过滤,所以只有登录在应用程序中的人才能访问它。 这是我的@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();
}

以下是我为此方法编写的过滤器:

@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() {
}}

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

Invalid <url-pattern> rest/projection/buy in filter mapping

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

2 个答案:

答案 0 :(得分:1)

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

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

在您的情况下,它不以&#34; /&#34;开头。如果使用servlet过滤器,则应该具有上下文根的绝对URL。添加&#34; /&#34;在一开始的时候。它应该工作。

答案 1 :(得分:0)

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

如果是Servlet过滤器,请发布您的servlet上下文以及JAX-RS资源的映射,以便找出出现错误的原因。

相关问题