Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?



import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet {
 ServletConfig sc = null;
 public void init(ServletConfig sc) throws ServletException {
  super.init(sc);
  this.sc = sc;
 }
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String dname = sc.getInitParameter("dname");
  String url = sc.getInitParameter("url");
  String tab = sc.getInitParameter("tab");
  try {
   Class.forName(dname);
   Connection con = DriverManager.getConnection(url, "scott", "tiger");
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from " + tab);
   while (rs.next()) {
    pw.println("<h2>" + rs.getString(1) + "" + rs.getString(2) + "" + rs.getString(3) + "</h2>");
   }
   con.close();
  } catch (Exception e) {
   res.sendError(503, "PROBLEM IN DATABASE...");
  }
 }
}



web.xml:


<web-app>

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>


No comments:

Post a Comment