How to create MySQL database connection in web.xml of Apache Tomcat using Struts 2

后端 未结 1 1509
星月不相逢
星月不相逢 2021-01-16 23:13

I want to make database connection at application level, so I want create connection in web.xml file of Apache tomcat server. I am developing our application us

相关标签:
1条回答
  • 2021-01-16 23:36

    Putting @Resource on the action bean property makes no sense. If you need more information about injecting resources you should read a tutorial. Instead create a ServletContextListener and put annotation there. On context initialized event set context attribute

    public class MyServletContextListener implements ServletContextListener {
    
      @Resource(name="jdbc/dbmy")
      private DataSource ds;
    
      @Override
      public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("contextInitialized");
        ServletContext context = servletContextEvent.getServletContext();
        context.setAttribute("ds",ds);
      }
    
      @Override
      public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("contextDestroyed");
    
      }
    }
    

    web.xml (should be in WEB-INF):

    <listener>
      <listener-class>com.servlet.MyServletContextListener</listener-class>
    </listener>
    

    now you can get datasource in the execute method

    ds = (DataSource)ServletActionContext.getServletContext().getAttribute("ds");
    
    0 讨论(0)
提交回复
热议问题