1.web.xml配置的参数

      <servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>com.Conservlet</servlet-class>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/house</param-value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>123456</param-value>
</init-param>
<init-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>

2.servlet的doGet()获取值

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
try {
ServletConfig config = getServletConfig();
String driver=config.getInitParameter("driver");
String url=config.getInitParameter("url");
String user=config.getInitParameter("user");
String pwd=config.getInitParameter("pwd");
response.setCharacterEncoding("gbk");
//注册驱动
Class.forName(driver);
//建立连接
Connection conn = (Connection)DriverManager.getConnection(url, user, pwd);
Statement stm = (Statement)conn.createStatement();
ResultSet rs = stm.executeQuery("select username,pwd from user");
response.setContentType("text/html;charset=gbk");
PrintStream out = new PrintStream(response.getOutputStream());
out.println("<html>");
out.println("<head>");
out.println("<title>测试连接</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border=\"1\" width=\"300\"");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
// TODO: handle exception
}
}
05-16 23:08