2010-06-09 58 views
0

上下文參數我已經在web.xml中的過濾器和參數JAVA:無法獲得在篩選

的web.xml是這樣的:

<filter> 
    <description> 
    </description> 
    <display-name>AllClassFilter</display-name> 
    <filter-name>AllClassFilter</filter-name> 
    <filter-class>com.datval.homework.AllClassFilter</filter-class> 
    <init-param> 
     <param-name>DB_URL</param-name> 
     <param-value>jdbc:derby:C:/Users/admin/workspace/homework03/homework/databases/StudentsDB;create=true</param-value> 
    </init-param> 
    <init-param> 
     <param-name>DB_DIALECT</param-name> 
     <param-value>org.hibernate.dialect.DerbyDialect</param-value> 
    </init-param> 
    <init-param> 
     <param-name>DB_DRIVER</param-name> 
     <param-value>org.apache.derby.jdbc.EmbeddedDriver</param-value> 
    </init-param> 
</filter> 

測繪工作良好。 但我無法在我的過濾器中獲取此參數。

public void init(FilterConfig config) throws ServletException { 
    // TODO Auto-generated method stub 
    debugMessage = config.getInitParameter("debugMessage"); 
    ctx = config.getServletContext(); 
} 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
    // TODO Auto-generated method stub 
    // place your code here 

    ctx.log("Start - " + debugMessage); 
    String myDbUrl = ctx.getInitParameter("DB_URL"); 
    String DB_DIALECT = ctx.getInitParameter("DB_DIALECT"); 
    String DB_DRIVER = ctx.getInitParameter("DB_DRIVER"); 

    Map<String,String> pr = new HashMap<String,String>(); 
    pr.put("hibernate.connection.url", myDbUrl); 
    pr.put("hibernate.dialect", DB_DIALECT); 
    pr.put("hibernate.connection.driver_class", DB_DRIVER); 

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("students",pr); 
    EntityManager em = emf.createEntityManager(); 
    request.setAttribute("em", em); 
    chain.doFilter(request, response); 
    em.close(); 
    ctx.log("end - " + debugMessage); 
} 

我已檢查並且myDbUrl爲空。我做錯了什麼?任何想法? 對不起代碼,我稍後會改變它:)

回答

5

DB_URL是在FilterConfig一個參數,而不是ServletContext。從傳遞給init()方法的FilterConfig實例中訪問它。

+0

:( 謝謝,我已經複製了部分代碼,並沒有注意到這:( – DaTval 2010-06-09 20:12:38