Java EE WEB工程师培训——JDBC+Servlet+JSP整合开发之21.Servlet_资源访问(访问数据库)

本文涉及的产品
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:
? B/S结构程序、B/A/S结构程序简介 
? Servlet 资源访问 
–Servlet 和 JDBC 
? 实例 
–维护客户列表
#######################################
? B/S结构程序、B/A/S结构程序简介 
–B/S结构程序是指:Browser(客户端)/Server(服务器)两层结构 
–B/A/S结构程序是指:Browser(客户端)/Application Server(应用程序服务器)/DB Server 三层结构
? Servlet 资源访问 
–Servlet 和 JDBC 
? Servlet作为控制器 
–响应用户请求 
? 获得表单数据 
–调用后台逻辑 
? 业务逻辑 
? 数据逻辑 
–页面导航 
? JDBC 
–使用DAO模式封装数据逻辑(封装持久层)
 
? 实例 
–维护客户列表
image
DBServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    
import java.sql.Connection;    
import java.sql.DriverManager;    
import java.sql.ResultSet;    
import java.sql.SQLException;    
import java.sql.Statement;    

import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

public  class DBServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public DBServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request    
         *                        the request send by the client to the server    
         * @param response    
         *                        the response send by the server to the client    
         * @throws ServletException    
         *                         if an error occurred    
         * @throws IOException    
         *                         if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request, response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to    
         * post.    
         *    
         * @param request    
         *                        the request send by the client to the server    
         * @param response    
         *                        the response send by the server to the client    
         * @throws ServletException    
         *                         if an error occurred    
         * @throws IOException    
         *                         if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                 // jdbc    
                 // get Connection    
                Connection conn =  null;    
                 // 加载驱动    
                 try {    
                        Class.forName( "com.mysql.jdbc.Driver");    
                        conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/Servlet_db", "root", "963963");    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                // get Statement    
                ResultSet rs = null;    
                try {    
                        Statement stmt = conn.createStatement();    
                        String sql = "select * from customertbl";    
                        rs = stmt.executeQuery(sql);    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }    

                response.setContentType("text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.println("    <table>");    
                out.println("    <tr>");    

                out.println("    <th>");    
                out.println("ID");    
                out.println("    </th>");    

                out.println("    <th>");    
                out.println("Name");    
                out.println("    </th>");    

                out.println("    <th>");    
                out.println("Email");    
                out.println("    </th>");    

                try {    
                        while (rs.next()) {    
                                int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String email = rs.getString(3);    
                                out.println("    <tr>");    
                                out.println("    <td>");    
                                out.println(id);    
                                out.println("    </td>");    
                                out.println("    <td>");    
                                out.println(name);    
                                out.println("    </td>");    
                                out.println("    <td>");    
                                out.println(email);    
                                out.println("    </td>");    
                                out.println("    </tr>");    
                        }    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally {    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    

                out.println("    </tr>");    
                out.println("    </table>");    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException    
         *                         if an error occurs    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


web.xml 
image
测试
image 
以上代码实现了读取数据库数据功能,但是没有实现分层结构哈~下面我们实现分层结构来实现代码共用。
DBServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    
import java.sql.Connection;    
import java.sql.DriverManager;    
import java.sql.ResultSet;    
import java.sql.SQLException;    
import java.sql.Statement;    
import java.util.List;    

import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

import com.michael.dao.CustomerDao;    
import com.michael.dao.impl.CustomerDaoImpl;    
import com.michael.vo.Customer;    

public  class DBServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public DBServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request    
         *                        the request send by the client to the server    
         * @param response    
         *                        the response send by the server to the client    
         * @throws ServletException    
         *                         if an error occurred    
         * @throws IOException    
         *                         if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request, response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to    
         * post.    
         *    
         * @param request    
         *                        the request send by the client to the server    
         * @param response    
         *                        the response send by the server to the client    
         * @throws ServletException    
         *                         if an error occurred    
         * @throws IOException    
         *                         if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                 /*    
                // jdbc    
                // get Connection    
                Connection conn = null;    
                // 加载驱动    
                try {    
                        Class.forName("com.mysql.jdbc.Driver");    
                        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Servlet_db", "root", "963963");    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                // get Statement    
                ResultSet rs = null;    
                try {    
                        Statement stmt = conn.createStatement();    
                        String sql = "select * from customertbl";    
                        rs = stmt.executeQuery(sql);    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }    
                */
    
                CustomerDao dao =  new CustomerDaoImpl();    
                List list = dao.getCustomerList();    

                response.setContentType( "text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.println("    <table>");    
                out.println("    <tr>");    

                out.println("    <th>");    
                out.println("ID");    
                out.println("    </th>");    

                out.println("    <th>");    
                out.println("Name");    
                out.println("    </th>");    

                out.println("    <th>");    
                out.println("Email");    
                out.println("    </th>");    
                /*    
                try {    
                        while (rs.next()) {    
                                int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String email = rs.getString(3);    
                                out.println("    <tr>");    
                                out.println("    <td>");    
                                out.println(id);    
                                out.println("    </td>");    
                                out.println("    <td>");    
                                out.println(name);    
                                out.println("    </td>");    
                                out.println("    <td>");    
                                out.println(email);    
                                out.println("    </td>");    
                                out.println("    </tr>");    
                        }    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally {    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                */
    
                for (int i=0;i<list.size();i++){    
                        Customer c = (Customer) list.get(i);    
                        out.println("    <tr>");    
                        out.println("    <td>");    
                        out.println(c.getId());    
                        out.println("    </td>");    
                        out.println("    <td>");    
                        out.println(c.getName());    
                        out.println("    </td>");    
                        out.println("    <td>");    
                        out.println(c.getEmail());    
                        out.println("    </td>");    
                        out.println("    </tr>");    
                }    
                out.println("    </tr>");    
                out.println("    </table>");    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException    
         *                         if an error occurs    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


CustomerDaoImpl
image
ConnectionUtil 
package com.michael.dao.impl;    

import java.sql.Connection;    
import java.sql.DriverManager;    
import java.util.Properties;    

public  class ConnectionUtil {    

         /**    
         * @param args    
         */
    
         public  static  void main(String[] args) {    
                ConnectionUtil cu =  new ConnectionUtil();    
                System.out.println(cu.openConnection());    
        }    
         public Connection openConnection() {    
                String url = "";    
                String driver = "";    
                String user = "";    
                String password = "";    
                Properties prop =  new Properties();    
                 try {    
                        prop.load( this.getClass().getClassLoader().getResourceAsStream( "DBConfig.properties"));    
                        driver = prop.getProperty( "driver");    
                        url = prop.getProperty( "url");    
                        user = prop.getProperty( "user");    
                        password = prop.getProperty( "password");    
                        Class.forName(driver);    
                        Connection conn = DriverManager.getConnection(    
                                        url, user, password);    
                         return conn;    
                }  catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return  null;    
        }    
         public Connection getConnection(String driver, String url, String user,    
                        String password) {    
                 // Class.forName()    
                 try {    
                        Class.forName(driver);    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(url, user, password);    
                         return conn;    
                }  catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return  null;    
        }    

         public Connection getConnection() {    
                 // Class.forName()    
                 try {    
                        Class.forName( "com.mysql.jdbc.Driver");    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(    
                                         "jdbc:mysql://localhost:3306/Servlet_db", "root", "963963");    
                        return conn;    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                return null;    
        }    


DBConfig.properties 
image
Customer 
image 
测试
image
############################################





本文转自redking51CTO博客,原文链接:http://blog.51cto.com/redking/289971 ,如需转载请自行联系原作者
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
15天前
|
Java 程序员
【Java探索之旅】继承概念_语法_父类的成员访问
【Java探索之旅】继承概念_语法_父类的成员访问
28 10
|
19天前
|
安全 Java API
Java中的Servlet编程详解
Java中的Servlet编程详解
|
19天前
|
Java 数据库连接 开发者
Java中的Servlet生命周期详解
Java中的Servlet生命周期详解
|
23天前
|
Java 关系型数据库 MySQL
使用MySQL JDBC连接数据库
使用MySQL JDBC连接数据库
|
23天前
|
SQL 存储 Java
优化Java应用的数据库访问性能
优化Java应用的数据库访问性能
|
24天前
|
存储 NoSQL Java
探索Java分布式锁:在高并发环境下的同步访问实现与优化
【6月更文挑战第30天】Java分布式锁在高并发下确保数据一致性,通过Redis的SETNX、ZooKeeper的临时节点、数据库操作等方式实现。优化策略包括锁超时重试、续期、公平性及性能提升,关键在于平衡同步与效率,适应大规模分布式系统的需求。
30 1
|
13天前
|
SQL 安全 Java
Java面试题:什么是JDBC以及如何在Java中使用它进行数据库操作?
Java面试题:什么是JDBC以及如何在Java中使用它进行数据库操作?
17 0
|
14天前
|
SQL Java 关系型数据库
Java面试题:描述JDBC的工作原理,包括连接数据库、执行SQL语句等步骤。
Java面试题:描述JDBC的工作原理,包括连接数据库、执行SQL语句等步骤。
24 0
|
19天前
|
Java 应用服务中间件 Linux
Tomcat安装部署[单机软件],可以让用户开发的WEB应用程序,变成可以被访问的网页,Tomcat的使用需要jdk环境
Tomcat安装部署[单机软件],可以让用户开发的WEB应用程序,变成可以被访问的网页,Tomcat的使用需要jdk环境
|
19天前
|
Java 关系型数据库 MySQL
使用MySQL JDBC连接数据库
使用MySQL JDBC连接数据库