views:

142

answers:

1

Hello, I have a filter and parameters in web.xml

web.xml is like this:

    <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>

mapping is working well. But I can't get this parameters in my 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);
}

I have checked and myDbUrl is null. What I'm doing wrong? Any idea? Sorry about code, I will change it later :)

+4  A: 

DB_URL is a parameter in the FilterConfig, not the ServletContext. Access it from the FilterConfig instance passed to the init() method.

erickson
:(Thank you, I have copied some part of code and didn't noticed this :(
DaTval