我正在使用dropwizard 0.7.0,我想創建一個自定義篩選器。帶數據庫信息的自定義篩選器下拉向導
定製過濾器應檢查數據庫中是否存在令牌。 創建過濾器並在Application類中註冊該過濾器的正確方法是什麼?
我以前this question實現過濾器,這是工作,但是當我更改代碼這樣:
final AuthenticationDAO authenticationDAO = new AuthenticationDAO(hibernateBundle.getSessionFactory());
environment.servlets().addFilter("authenticationFilter", new AuthenticationFilter(authenticationDAO)).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/transaction/*");
這是我的過濾器:
public class AuthenticationFilter implements Filter {
private final AuthenticationDAO authenticationDAO;
public AuthenticationFilter(AuthenticationDAO authenticationDAO) {
this.authenticationDAO = authenticationDAO;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String authenticationToken = ((Request) servletRequest).getHeader(Constants.HEADER_TOKEN_PARAM_NAME);
HttpServletResponse response = (HttpServletResponse)servletResponse;
if(Strings.isNullOrEmpty(authenticationToken)){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else if(!authenticationDAO.findByAuthenticationToken(authenticationToken).isPresent()){
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
當過濾器將被訪問,我得到下面的錯誤,因爲沒有會話活動:
WARN [2014-04-22 14:37:42,733] org.eclipse.jetty.servlet.ServletHandler:/ test/show ! org.hibernate.HibernateException:沒有會話當前綁定到執行上下文 !在org.hibernate.context.internal.ManagedSessionContext.currentSession(ManagedSessionContext.java:75)〜[hibernate-core-4.3.1.Final.jar:4.3.1.Final] !在org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1013)〜[休眠 - 核心4.3.1.Final.jar:4.3.1.Final]
感謝您的回答,但這不是正確的答案,我應該添加一個url模式。該解決方案不會訪問過濾器。 –
我已經更新了我的答案。我自己使用這個解決方案。 – user2720917
訪問令牌檢查時也出現錯誤: org.hibernate.HibernateException:沒有會話當前綁定到執行上下文 –