2015-06-27 26 views
2

我有一個@POST休息方法,我想爲它做過濾器,所以只有在應用程序中登錄的人才能夠訪問它。 這裏是我的@POST方法:<url-pattern>在過濾器映射無效

@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 

我正在使用Jae-RS的TomEE服務器。有什麼辦法可以解決這個問題嗎?

回答

1

按照servlet規範的映射路徑應遵循的規則:

  • 目錄映射:的字符串開始用「/」字符,並用「/ *」後綴被用於路徑映射結束。
  • 擴展映射:以'*。'開頭的字符串用作擴展映射。
  • 上下文根:空字符串(「」)是一種特殊的URL模式,它準確映射到 應用程序的上下文根,即形式爲http://host:port/ /的請求。在這種情況下,路徑信息是'/',servlet路徑和上下文路徑是空字符串(「」)。
  • 默認Servlet:只包含'/'字符的字符串表示應用程序的「默認」servlet。在這種情況下,servlet路徑是請求URI減去上下文路徑,路徑信息爲空。
  • 準確映射:所有其他字符串僅用於精確匹配。

就你而言,它不以「/」開頭。如果您使用的是servlet過濾器,您應該擁有上下文根的絕對url。在開頭添加「/」。它應該工作。