Java Servlets

Servlets are protocol- and platform-independent server side
    components that can be dynamically loaded like applets
    or can be considered as server side counterpart to applets
    or Java application components which are loaded, on demand
    Servlets differ from applets in that they are faceless ( without
    any graphics ) can be invoked in many ways one of which of the form

Servlets can be used to return new Web-pages.
 



In General :
      eg Hello World Servlet:
    import java.io.*;
    import java.servlet.*;
    public class HelloWorldServlet extends GenericServlet {

        public void service(ServletRequest req, ServletResponseres)
            throws ServletException, IOException{
            PrintStream out = newPrintStream(res.getOutputStream());
            out.println("Hello world!");
        }

        public String getServletInfo() {
            return "Hello World Servlet";
        }
    }



Sevlets and Database Connectivity
Demonstrates how to use servlets to access the database Implementation :
    public class DBServlet extends HttpServlet {
        //overriding service method
        public void service(HttpServletRequest req,  HttpServletResponse res) throws ServletException,  IOException {
            //fetch the parameters from the form input
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String query = req.getParameter("query");
            PrintStream out = new PrintStream (res.getOutputStream() );
            String url = "jdbc:weblogic:oracle"; // JDBC driver url
            try {
                Class.forName("weblogic.jdbc.oci.Driver"); /* load the driver
                classes and get the connection to the database */
                Connection con =    DriverManager.getConnection(url,username,password);

                //create and execute the query statement
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                dispResultSet(rs,out);
                //close connections here
            } Catch(SQLException ex) { //print the exceptions caught }

        }
 

        private void dispResultSet(ResultSet rs, PrintStream out)  throws SQLException {
                //get the resultset metadata from the result set
                ResultSetMetaData rsmd = rs.getMetaData();
                //get the # of columns in the table and display the results
                while (rs.next() ) {
                    for (int I;I &#060= numcols; I++) {
                        //display the values for each column
                    }
                }
          }

 }