日期:2014-05-18 浏览次数:20723 次
package com.util;
public class connect extends HttpServlet
{
private Connection cn=null;
public void init(ServletConfig config)throws ServletException{
super.init(config);
String driver=config.getInitParameter("driver");
String url=config.getInitParameter("url");
String user=config.getInitParameter("user");
String password=config.getInitParameter("password");
// String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
// String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=J2EEStest";
// String user="JSsa";
// String password="st";
try {
Class.forName(driver);
cn=DriverManager.getConnection(url,user,password);
}catch(Exception e)
{
System.out.println("Init Error:"+e.getMessage());
}
}
public void destroy(){
super.destroy();
try{
if(cn!=null&&(!cn.isClosed()))
{
cn.close();
cn=null;
}
}catch(Exception e) {
System.out.println("Destroy Error:"+e.getMessage());
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out=response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("<BODY>");
try {
String sql="select ename,job,sal,hiredate from emp";
PreparedStatement ps=cn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
out.print("<hl>员工列表</hl>");
out.print("<table border='1'>");
out.print("<tr>");
out.print("<td>姓名</td><td>职位</td><td>工资</td><td>加入公司日期</td>");
out.print("<tr>");
while(rs.next()) {
out.print("<tr>");
out.println("<td>"+rs.getString("ENAME")+"</td>");
out.println("<td>"+rs.getString("JOB")+"</td>");
out.println("<td>"+rs.getDouble("sal")+"</td>");
out.println("<td>"+rs.getString("hiredate")+"</td>");
out.print("<tr>");
}
rs.close();
ps.close();
out.print("</table>");
}catch(Exception e) {
out.println("<h2>处理请求发生错误:"+e.getMessage()+"</h2>");
}
out.println("</BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
this.doGet(request,response);
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
&nbs