1. Connect the MySQL database, select the Name field, and place the class file in the Tomcat installation file directory/webapps/test/web-inf/classes
1 Importjavax.servlet.ServletException;2 ImportJavax.servlet.http.HttpServlet;3 Importjavax.servlet.http.HttpServletRequest;4 ImportJavax.servlet.http.HttpServletResponse;5 6 Public classShowrsextendsHttpServlet {7 8 @Override9 protected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {Ten OneConnection conn =NULL; AStatement stmt =NULL; -ResultSet rs =NULL; - theResp.setcontenttype ("text/html"); -Resp.setcharacterencoding ("UTF8"); -PrintWriter out =Resp.getwriter (); - +Out.println ("<table border=1>"); -Out.println ("<tr><td>Content:</td></tr>"); + A Try { atClass.forName ("Com.mysql.jdbc.Driver"); -conn = Drivermanager.getconnection ("Jdbc:mysql://localhost/spring?user=root&password=root"); -stmt =conn.createstatement (); -rs = Stmt.executequery ("SELECT * from teams"); - while(Rs.next ()) { -Out.println ("<tr>"); inOut.println ("<td>" + rs.getstring ("name") + "</td>"); -Out.println ("</tr>"); to } +Out.println ("</table>"); - the}Catch(ClassNotFoundException e) { * //TODO auto-generated Catch block $ e.printstacktrace ();Panax Notoginseng}Catch(SQLException e) { - //TODO auto-generated Catch block the e.printstacktrace (); + } A the } + -}
2. Configure the Web. xml file with the path in/webapps/test/web-inf
<servlet> <servlet-name>ShowRs</servlet-name> <servlet-class>showrs </servlet-class> </servlet> <servlet-mapping> <servlet-name> showrs</servlet-name> <url-pattern>/ShowRs</url-pattern> </servlet-mapping>
3. Add Mysql-connector-java-xxx.jar to/webapps/test/web-inf/lib
4. Open the Web to test and show success!
4.1 Database table Teams original content
4.2 Name field accessed through the servlet
How to access the MySQL database using a servlet