package helloworld; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** */ @WebServlet("/HelloWorld") public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public HelloWorld() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = null; Statement stmt = null; ResultSet rs = null; response.setContentType("text/html"); response.setCharacterEncoding("gb2312"); PrintWriter out = response.getWriter(); out.println("<table border=1>"); out.println("<tr><td>查询结果</td></tr>"); try{ Class.forName("com.mysql.jdbc.Driver"); //lib conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gs?user=root&password=root"); stmt = conn.createStatement(); rs = stmt.executeQuery("select * from user"); while(rs.next()){ out.println("<tr>"); out.println("<td>"+rs.getString("name")+"</td>"); out.println("</tr>"); } out.println("</table>"); }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (SQLException e){ e.printStackTrace(); } finally{ try{ if(rs !=null){ rs.close(); rs=null; } if(stmt != null){ stmt.close(); stmt=null; } if(conn!=null){ conn.close(); conn=null; } } catch(SQLException e){ e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html><head><title>helloworld</title><head><body>hello world!!!</body></html>"); } }
时间: 2024-10-17 07:33:21