query1mysql.java

来自「java web 开发,Java Xml 编程指南书籍源码」· Java 代码 · 共 60 行

JAVA
60
字号
// servlet Query1 as extensible 3tier example, similar to
// Query0 but with sparts split off into three classes,
// one to know about file logging, one to know about
// database communication, one to know about HTML.

// This version adapted for mySQL, again by changing the name,
// dbUrl, driverName, and making sure there's no semi-colon
// on the end of a query.

import javax.servlet.*;  // communicate with client
import javax.servlet.http.*; 

import MyNa.utils.Logger;  // saves admin/debug info to file

import MyNa.utils.LookerUpperMySQL;   // communicate with database
import MyNa.utils.MiscDB;   // communicate with database
import MyNa.utils.HtmlWrapper;

import java.sql.SQLException;   // thrown by LookerUpper
import java.io.IOException; // thrown by HtmlWrapper


public class Query1MySQL extends HttpServlet { 
  String qString=
     "SELECT theNumber,theAddr FROM PHONEBOOK WHERE theName=?";
  Logger lg=null; LookerUpperMySQL looker=null;
    String driverName="org.gjt.mm.mysql.Driver";
    String dbUrl="jdbc:mysql://localhost/PHONEBOOK/";

  public void init(ServletConfig cfg) throws ServletException{
    super.init(cfg);
    try{
      lg=new Logger(); lg.clearLog(); lg.logIt("Query1.init()");
      looker=new LookerUpperMySQL(driverName,dbUrl,qString,lg);
    }catch(Exception E){E.printStackTrace(); lg.logIt(""+E);}
  }

  public void destroy(){ //  try to close up.
   lg.logIt("Query1.destroy()");
   looker.close();
  }

  public void doGet (HttpServletRequest req, 
                     HttpServletResponse res)
    throws ServletException, IOException{
   res.setContentType("text/html");
   String theName=req.getParameter("theName");
   
   String [][]resp=MiscDB.resultRowsToStringMatrix(looker.lookup(theName));
     // ask for THENUMBER (in PHONEBOOK) where THENAME= theName
      // a database query response is normally two-dimensional
   HtmlWrapper W=new HtmlWrapper(res.getWriter());
   W.wrapTablePage("Phone Number for "+theName,resp);
  }

  public String getServletInfo() {
    return "A simple 3tier system's servlet";
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?