Karen Goh Karen Goh - 6 months ago 32
Java Question

How do I put listener in web.xml java?

I have created web application and I'd like to know where do I put my listener in the web.xml.

<servlet>
<servlet-name>ProcessReg</servlet-name>
<servlet-class>ProcessReg</servlet-class>
<init-param>
<param-name>pract123</param-name>
<param-value>jdbc:odbc:practODBC</param-value>
</init-param>
<listener>
<listener-class>config</listener-class>
</listener>
</servlet>


The error message I received is:

cvc-complex-type.2.4.a: Invalid content was found starting with element 'listener'. One of '{"http://java.sun.com/xml/ns/javaee":init-param, "http://java.sun.com/xml/ns/javaee":load-on-startup, "http://java.sun.com/xml/ns/javaee":run-as, "http://java.sun.com/xml/ns/javaee":security-role-ref}' is expected. [17]


Here's my config file:

public class config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private DataSource dataSource;

@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
String databaseName = servletContext.getInitParameter("pract123");
try {
dataSource = (DataSource) new InitialContext().lookup("java:/comp /env/jdbc/TestDB");
} catch (NamingException e) {
throw new RuntimeException("Config failed: datasource not found", e);
}}

@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}

public DataSource getDataSource() {
return dataSource;
}

public static config getInstance(ServletContext servletContext) {
return (config) servletContext.getAttribute(ATTRIBUTE_NAME);
}
}

Answer

What you are doing is you are mixing up the <servlet> and <listener> tags .They should be seperate.

That should be

<servlet>
    <servlet-name>ProcessReg</servlet-name>
    <servlet-class>ProcessReg</servlet-class>
    <init-param>
        <param-name>pract123</param-name>
        <param-value>jdbc:odbc:practODBC</param-value>
    </init-param>       
  </servlet>

<listener>
        <listener-class>fully.qaulified.path.ContextListener</listener-class>
</listener>

or

<listener>
          <listener-class>fully.qaulified.path.ContextListener</listener-class>
 </listener>

<servlet>
    <servlet-name>ProcessReg</servlet-name>
    <servlet-class>ProcessReg</servlet-class>
    <init-param>
        <param-name>pract123</param-name>
        <param-value>jdbc:odbc:practODBC</param-value>
    </init-param>       
  </servlet>

And In your class

package fully.qaulified.path;
public class ContextListener implements ServletContextListener {
..
..

As a side note:

In Java, class names start's with capital letters. public class config should be

public class Config 
Comments