Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package web.mvc.servlets; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.context.support.WebApplicationContextUtils; import web.mvc.models.InfoItem; /** * * @author CodeFire */ @WebServlet("/servlet-info") public class MyServlet extends HttpServlet /* implements ApplicationContextAware */ { // private ApplicationContext context; // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); if (context == null) { request.getRequestDispatcher("WEB-INF/jsp/db-info-error.jsp").forward(request, response); } DriverManagerDataSource dataSource = context.getBean(DriverManagerDataSource.class); List<InfoItem> data = new ArrayList<>(); try { fillDataFromDataSource(data, dataSource); } catch (SQLException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("info", data); request.getRequestDispatcher("WEB-INF/jsp/db-info.jsp").forward(request, response); } private void fillDataFromDataSource(List<InfoItem> data, DriverManagerDataSource dataSource) throws SQLException { try (Connection connect = dataSource.getConnection()) { DatabaseMetaData metaData = connect.getMetaData(); data.add(new InfoItem("database name", metaData.getDatabaseProductName())); data.add(new InfoItem("database version", metaData.getDatabaseProductVersion())); data.add(new InfoItem("driver name", metaData.getDriverName())); data.add(new InfoItem("driver version", metaData.getDriverVersion())); } } }