servlet连接mysql小程序
1.我们会自己编写java代码与mysql通信,但是怎么在网络的环境下,用servlet去跟mysql连接
2.在基本的servlet程序下,我们再添加连接数据库的部分
1 import javax.servlet.http.HttpServlet; 2 import javax.servlet.http.HttpServlet;import java.io.IOException; 3 import java.io.*; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 public class httpservlet extends HttpServlet { 7 8 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{ 9 PrintWriter out =resp.getWriter(); 10 out.println("<html><head><head/><body><h1>hello<h1><body/><html/>"); 11 out.flush(); 12 out.close(); 13 } 14 15 16 17 18 19 20 }
3.先想一下为什么跟数据库连接,数据库连接的部分添在哪里.
跟数据库是在服务器端输出结果之前需要做的事情,就是out.printn那一段。我们需要调取数据库中的数据,再进行决策,然后输出请求结果。
4.编译代码
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 import java.util.Properties; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServlet;import java.io.IOException; 7 import java.io.*; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 public class ServletMysql extends HttpServlet { 11 12 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{ 13 14 try { 15 // The newInstance() call is a work around for some 16 // broken Java implementations 17 18 Class.forName("com.mysql.jdbc.Driver").newInstance(); 19 System.out.println("heo"); 20 Connection conn = 21 DriverManager.getConnection("jdbc:mysql://localhost/test?" + 22 "user=root&password=root"); 23 24 25 26 27 28 29 System.out.println(conn); 30 PrintWriter out =resp.getWriter(); 31 out.println("<html><head><head/><body><h1>hello<h1><body/><html/>"); 32 out.flush(); 33 out.close(); 34 35 } catch (Exception ex) { 36 // handle the error 37 } 38 39 40 41 42 43 44 45 }
5.将servlet小程序class文件放入tomcat容器中(见我的博客,基于servlet编程)
6,如何在输入框中输入什么,能让tomcat执行我们的servletmysql的calss文件呢,那就是web.xml的配置了
<servlet> <servlet-name>twoservlet</servlet-name> <servlet-class>ServletMysql</servlet-class> </servlet> <servlet-mapping> <servlet-name>twoservlet</servlet-name> <url-pattern>/mysql</url-pattern> </servlet-mapping>
7.根据自己的项目设置,输入正确的地址(我的是http://127.0.0.1:8080/myweb/mysql)
8.结果(在服务器端输出连接的信息,说明数据库连接成功)