jsp模仿QQ空间说说的发表

时间:2021-06-02 09:45:28

1.在文本域中输入文字(可以不添加)

2.点击添加图片(可以不添加)

3.点击发表

4.发表成功,文字和图片是超链接,点击就可以查看全部内容

5.点击图片查看原图,没有图片则不显示查看原图的超链接

主要用到的知识有:

图片的上传,session,JavaScript

主要思路:图片上传到服务器,获得图片的名字,就可以用img标签来显示,src就可以有路径了,文字保存在session,获得即可

代码随后上传

主页面

jsp模仿QQ空间说说的发表

添加文字图片

jsp模仿QQ空间说说的发表

点击发表后的页面

jsp模仿QQ空间说说的发表

任意点击图片或者文字,查看全文

jsp模仿QQ空间说说的发表

 fileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/fileupload.css">
</head>
<body>
    <div class="title_img">
        <img src="../images/send_message.png" />
    </div>
    <div class="message_main_div">
        <form action="../upload" method="post" enctype="multipart/form-data">

            <textarea id="text" cols="65" rows="18" name="message"></textarea>
            <hr class="hr14">
            <a href="javascript:;" class="file">添加图片 <input type="file"
                name="file1" id=""
                accept=".jpg,bmp,.gig,.png,.tif,.rgb,.dib,.eps,.jpe,.pcx,.bmp,.gif">
            </a>
            <hr class="hr14">
            <input type="submit" class="btn-style-03" value="发表" />
        </form>
    </div>

</body>
</html>

UploadServlet.java

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.auuzee.dao.MessageDao;
import com.auuzee.dao.UserDao;
import com.auuzee.dbutil.DBUtil;
import com.auuzee.entity.User;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

@WebServlet(urlPatterns = { "/upload" }, initParams = { @WebInitParam(name = "savePath", value = "upload") })
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 上传文件的保存路径
    String savePath = null;
    MessageDao md = new MessageDao();
    UserDao ud = new UserDao();

    public UploadServlet() {
        super();
    }

    public void init(ServletConfig config) throws ServletException {
        // 获取上传文件的保存路径
        savePath = config.getInitParameter("savePath");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user1 = new User();
        user1 = (User) request.getSession().getAttribute("user");
        String userName = user1.getUserName();
        String theLastImg = "";
        String dbImg = "";
        request.setCharacterEncoding("utf-8");
        String message = request.getParameter("message");
        if (message == null || "".equals(message) || message.trim() == null) {
            message = null;
        } else {
            // 进行文本处理
            String s1 = "\n";
            if (message.contains("\n")) {
                message = message.replaceAll(s1, "<br>");
            }
        }
        String fileName = null;
        // 获得页面封装的Part对象
        Part part = request.getPart("file1");

        // 获得请求头(包含了文件名)
        String header = part.getHeader("content-disposition");
        // 从请求头中获得文件名
        fileName = getFileName(header);
        // System.out.println("fileName是" + fileName + "啥");
        if ("".equals(fileName) || fileName == null || fileName == "") {
            System.out.println("fileName文件名是null");
        } else {
            System.out.println("fileName文件名不是null");
            if (fileName.endsWith(".jpg") || fileName.endsWith(".bmp") || fileName.endsWith(".gig")
                    || fileName.endsWith(".png") || fileName.endsWith(".tif") || fileName.endsWith(".rgb")
                    || fileName.endsWith(".dib") || fileName.endsWith(".eps") || fileName.endsWith(".jpe")
                    || fileName.endsWith(".pcx") || fileName.endsWith(".bmp") || fileName.endsWith(".gif")) {
                // 获得服务器存储上传文件的真实路径
                String realSavePath = request.getServletContext().getRealPath(savePath);

                System.out.println("realSavePath:" + realSavePath);
                // 向服务器保存路径上传文件

                // 在upload下面以用户的名字建立文件夹,
                String imgFile = realSavePath + "/" + userName;
                System.out.println(imgFile);
                File newFolder = new File(imgFile);
                if (!newFolder.exists() && !newFolder.isDirectory()) {
                    System.out.println("//图片文件夹不存在");
                    newFolder.mkdir();
                } else {
                    System.out.println("//图片文件夹存在");
                }
                dbImg = userName + "_" + System.currentTimeMillis() + "_" + fileName;
                theLastImg = imgFile + "/" + dbImg;
                dbImg = "upload" + "/" + userName + "/" + dbImg;

                System.out.println("图片的最终路径是:" + theLastImg);
                part.write(theLastImg);

            }
        }
        request.getSession().setAttribute("message", message);

        // 为每个用户的用户名设置文件夹
        String targetFileName = "C:/Users/p8780/Desktop/file/file/" + userName;
        File newFileName = new File(targetFileName);

        if (!newFileName.exists() && !newFileName.isDirectory()) {
            System.out.println("//不存在");
            newFileName.mkdir();
        } else {
            System.out.println("//目录存在");
        }
        // 在这个用户文件夹下生成txt文件,文件名字为当前时间戳
        String targetTxt;
        if (message != null) {
            targetTxt = targetFileName + "/" + userName + System.currentTimeMillis() + ".txt";
            File file1 = new File(targetTxt);
            if (!file1.exists()) {
                try {
                    file1.createNewFile();
                } catch (IOException e) {
                }
            } else {
                targetTxt = null;
            }
            String str = message;
            fileCopyByStreamArray(str, targetTxt);
            // 通过用户名查询用户的Id;
            int userId = ud.selectUserId(userName);
            // 把文本文件的名字,和图片的名字保存在数据库中
            md.addMessage(targetTxt, dbImg, userId);

            request.getSession().setAttribute("realSavePath", fileName);
            response.sendRedirect("jsp/userlist.jsp");
            /*
             * request.getRequestDispatcher("jsp/userlist.jsp").forward(request,
             * response);
             */
        }
    }

    @SuppressWarnings("unused")
    public static void fileCopyByStreamArray(String str, String targetFile)
            throws UnsupportedEncodingException, FileNotFoundException {
        System.out.println("正在写文件....");
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        File file1 = new File(targetFile);
        fos = new FileOutputStream(file1);
        osw = new OutputStreamWriter(fos, "UTF-8");
        try {
            byte[] b = new byte[1000];
            b = str.getBytes();
            int length = b.length;
            fos.write(b, 0, length);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 通过请求头解析文件名
    private String getFileName(String header) {
        System.out.println("header:" + header);
        // header:form-data; name="file1";
        // filename="D:\Document And Settings2\hpe\Desktop\servletapi.zip"
        String[] tmp1 = header.split(";");
        String[] tmp2 = tmp1[2].split("=");
        String fileName = tmp2[1].substring(tmp2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        System.out.println("fileName:" + fileName + "接受");

        if (fileName == null || fileName == "") {
            System.out.println("fileName是null");
        }
        return fileName;
    }
}

fileupload.css

* {
    margin: 0;
    padding: 0;
}

body {
    font: 12px  Verdana, Arial, Geneva, sans-serif;
    color: #404040;
    background-color:#abcdef;
    background: url(../images/send_bg.jpg) no-repeat top center;
    background-size: cover;
}

.message_main_div {
    margin: 20px auto;
    width: 384px;
}

.file {
    position: relative;
    display: inline-block;
    background: #FCFCFC;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}

.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}

.file:hover {
    cousor: pointer;
    text-decoration: none;
}

.btn-style-03 {
    border-style: none;
    padding: 8px 30px;
    line-height: 24px;
    color: #fff;
    font: 16px "Microsoft YaHei", Verdana, Geneva, sans-serif;
    cursor: pointer;
    margin-left: 95%;
}

.btn-style-03 {
    border: 1px #029e4f solid;
    -webkit-box-shadow: inset 0px 0px 1px #fff;
    -moz-box-shadow: inset 0px 0px 1px #fff;
    box-shadow: inset 0px 0px 1px #fff;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    text-shadow: 1px 1px 0px #45a1d6;
    background-color: #0fda74;
    background-image: -webkit-gradient(linear, 0 0%, 0 100%, from(#0fda74),
        to(#05c263));
    background-image: -webkit-linear-gradient(top, #0fda74 0%, #05c263 100%);
    background-image: -moz-linear-gradient(top, #0fda74 0%, #05c263 100%);
    background-image: -ms-linear-gradient(top, #0fda74 0%, #05c263 100%);
    background-image: -o-linear-gradient(top, #0fda74 0%, #05c263 100%);
    background-image: linear-gradient(top, #0fda74 0%, #05c263 100%);
}

.btn-style-03:hover {
    background-color: #05c263;
    background-image: -webkit-gradient(linear, 0 0%, 0 100%, from(#05c263),
        to(#0fda74));
    background-image: -webkit-linear-gradient(top, #05c263 0%, #0fda74 100%);
    background-image: -moz-linear-gradient(top, #05c263 0%, #0fda74 100%);
    background-image: -ms-linear-gradient(top, #05c263 0%, #0fda74 100%);
    background-image: -o-linear-gradient(top, #05c263 0%, #0fda74 100%);
    background-image: linear-gradient(top, #05c263 0%, #0fda74 100%);
}

#text {
    resize: none;
}

a {
    text-decoration: none;
}

.hr14 {
    height: 10px;
    border: none;
}
.title_img{
    margin:0 auto;
    margin-top:60px;
    width:400px;
    text-align:left;

}

send_message.png

jsp模仿QQ空间说说的发表

send_bg.jpg

jsp模仿QQ空间说说的发表

效果图:

jsp模仿QQ空间说说的发表

messageDao.java

package com.auuzee.dao;

import com.auuzee.dbutil.DBUtil;
import com.auuzee.entity.Message;

public class MessageDao {
    DBUtil dbu = new DBUtil();

    Message ms = new Message();

    public int addMessage(String fileName, String imgName, int userId) {
        String sql = "insert into message (fileName,imgName,userId,messageTime) values('" + fileName + "','" + imgName
                + "','" + userId
                + "',sysdate )";// 一定要进行格式转换,Mysql中不用
        // 调用共通的增删改方法执行sql
        int count = dbu.update(sql, null);
        dbu.close();
        return count;
    }
}

message.java

package com.auuzee.entity;

public class Message {
    private String fileName;//发表的说说文件
    private String imgName;//发表的说说图片
    private int userId;//用户id
    private String messageTime;//发表时间
    private String userName;//用户名
    private int count;//浏览数
    private int love;//赞
    private int remark;//评论

    public int getRemark() {
        return remark;
    }

    public void setRemark(int remark) {
        this.remark = remark;
    }

    public int getLove() {
        return love;
    }

    public void setLove(int love) {
        this.love = love;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getImgName() {
        return imgName;
    }

    public void setImgName(String imgName) {
        this.imgName = imgName;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getMessageTime() {
        return messageTime;
    }

    public void setMessageTime(String messageTime) {
        this.messageTime = messageTime;
    }

}
 DBUtil里面封装的是数据库的连接配置信息。

 userDao.java

package com.auuzee.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.auuzee.dbutil.DBUtil;
import com.auuzee.entity.MeUser;
import com.auuzee.entity.Message;
import com.auuzee.entity.User;

public class UserDao {
    DBUtil dbu = new DBUtil();

    // 查询所有说说的总记录数
    public int selectUsersSize() {
        String sql = "select count(*) from message";
        ResultSet rs = dbu.select(sql, null);
        int size = 0;
        try {
            while (rs.next()) {
                size = rs.getInt(1);
            }
            return size;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        } finally {
            dbu.close();
        }
    }

    // 查询纯文本的总记录数
    public int selectPlainTextSize() {
        String sql = "select count(*) from message where imgName is null";
        ResultSet rs = dbu.select(sql, null);
        int size = 0;
        try {
            while (rs.next()) {
                size = rs.getInt(1);
            }
            return size;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        } finally {
            dbu.close();
        }
    }

    // 查询纯图片的总记录数
    public int selectPlainImgsSize() {
        String sql = "select count(*) from message where fileName is null";
        ResultSet rs = dbu.select(sql, null);
        int size = 0;
        try {
            while (rs.next()) {
                size = rs.getInt(1);
            }
            return size;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        } finally {
            dbu.close();
        }
    }

    // 查询图文结合的总记录数
    public int selectImgTextSize() {
        String sql = "select count(*) from message where imgName is not null and fileName is not null";
        ResultSet rs = dbu.select(sql, null);
        int size = 0;
        try {
            while (rs.next()) {
                size = rs.getInt(1);
            }
            return size;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        } finally {
            dbu.close();
        }
    }

    // 通过分页查询所有信息
    public List<Message> selectAllMessages(int currentPage, int pageSize) {
        String sql = "select * from (select a1.*,rownum rn from"
                + "(select * from message order by messageTime desc) a1 where rownum <=?) where rn>=?";
        Object[] param1;
        if (currentPage == 1) {
            Object[] param = { pageSize, 1 };
            param1 = param;
        } else {
            Object[] param = { currentPage * pageSize, (currentPage - 1) * pageSize + 1 };
            param1 = param;
        }
        ResultSet rs = dbu.select(sql, param1);
        List<Message> messageList = new ArrayList<Message>();
        SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            while (rs.next()) {
                Message message = new Message();
                message.setFileName(rs.getString("fileName"));
                message.setImgName(rs.getString("imgName"));
                message.setMessageTime(myFmt.format(rs.getTimestamp("messageTime")));
                message.setUserId(rs.getInt("userId"));
                // 得到喜欢和赞的人数
                message.setLove(rs.getInt("love"));
                message.setRemark(rs.getInt("remark"));
                message.setCount(rs.getInt("count") + 1);
                String time = rs.getTimestamp("messageTime") + "";
                time = time.substring(0, time.length() - 2);
                addCount(time, rs.getInt("userId"));
                messageList.add(message);
            }
            return messageList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            dbu.close();
        }
    }

    // 通过发表时间增加浏览次数
    public void addCount(String messageTime, int userId) throws SQLException {
        // 查询之前先加1
        String sql = "update message set count=count+1 where userId=? and messageTime=to_date(?,'yyyy-mm-dd hh24:mi:ss')";
        System.out.println("sql是" + sql);
        Object[] param1 = { userId, messageTime };
        int count = dbu.update(sql, param1);
        if (count > 0) {
            System.out.println("数据库中添加一条浏览信息成功");
        }
    }

    // 通过分页查询文本信息
    public List<Message> selectAllTextMessages(int currentPage, int pageSize) {
        String sql = "select * from (select a1.*,rownum rn from"
                + "(select * from message where imgName is null order by messageTime desc) a1 where rownum <=?) where rn>=?";
        Object[] param1;
        if (currentPage == 1) {
            Object[] param = { pageSize, 1 };
            param1 = param;
        } else {
            Object[] param = { currentPage * pageSize, (currentPage - 1) * pageSize + 1 };
            param1 = param;
        }
        ResultSet rs = dbu.select(sql, param1);
        List<Message> messageList = new ArrayList<Message>();
        SimpleDateFormat myFmt = new SimpleDateFormat("MM-dd HH:mm:ss");
        try {
            while (rs.next()) {
                Message message = new Message();
                message.setFileName(rs.getString("fileName"));
                message.setImgName(rs.getString("imgName"));
                message.setMessageTime(myFmt.format(rs.getTimestamp("messageTime")));
                message.setUserId(rs.getInt("userId"));
                message.setCount(rs.getInt("count") + 1);
                String time = rs.getTimestamp("messageTime") + "";
                time = time.substring(0, time.length() - 2);
                addCount(time, rs.getInt("userId"));
                messageList.add(message);
            }
            return messageList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            dbu.close();
        }
    }

    // 通过分页查询图片信息
    public List<Message> selectAllImgsMessages(int currentPage, int pageSize) {
        String sql = "select * from (select a1.*,rownum rn from"
                + "(select * from message where fileName is null  order by messageTime desc) a1 where rownum <=?) where rn>=?";
        Object[] param1;
        if (currentPage == 1) {
            Object[] param = { pageSize, 1 };
            param1 = param;
        } else {
            Object[] param = { currentPage * pageSize, (currentPage - 1) * pageSize + 1 };
            param1 = param;
        }
        ResultSet rs = dbu.select(sql, param1);
        List<Message> messageList = new ArrayList<Message>();
        SimpleDateFormat myFmt = new SimpleDateFormat("MM-dd HH:mm:ss");
        try {
            while (rs.next()) {
                Message message = new Message();
                message.setFileName(rs.getString("fileName"));
                message.setImgName(rs.getString("imgName"));
                message.setMessageTime(myFmt.format(rs.getTimestamp("messageTime")));
                message.setUserId(rs.getInt("userId"));
                message.setCount(rs.getInt("count") + 1);
                String time = rs.getTimestamp("messageTime") + "";
                time = time.substring(0, time.length() - 2);
                addCount(time, rs.getInt("userId"));
                messageList.add(message);
            }
            return messageList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            dbu.close();
        }
    }

    // 通过分页查询图文信息
    public List<Message> selectAllTextImgsMessages(int currentPage, int pageSize) {
        String sql = "select * from (select a1.*,rownum rn from"
                + "(select * from message where fileName is not null and imgName is not null order by messageTime desc) a1 where rownum <=?) where rn>=?";
        Object[] param1;
        if (currentPage == 1) {
            Object[] param = { pageSize, 1 };
            param1 = param;
        } else {
            Object[] param = { currentPage * pageSize, (currentPage - 1) * pageSize + 1 };
            param1 = param;
        }
        ResultSet rs = dbu.select(sql, param1);
        List<Message> messageList = new ArrayList<Message>();
        SimpleDateFormat myFmt = new SimpleDateFormat("MM-dd HH:mm:ss");
        try {
            while (rs.next()) {
                Message message = new Message();
                message.setFileName(rs.getString("fileName"));
                message.setImgName(rs.getString("imgName"));
                message.setMessageTime(myFmt.format(rs.getTimestamp("messageTime")));
                message.setUserId(rs.getInt("userId"));
                message.setCount(rs.getInt("count") + 1);
                String time = rs.getTimestamp("messageTime") + "";
                time = time.substring(0, time.length() - 2);
                addCount(time, rs.getInt("userId"));
                messageList.add(message);
            }
            return messageList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            dbu.close();
        }
    }

    // 通过Id查询User表中的基本信息,直接保存在合并的实体类对象中
    public void selectUserName(int userId, MeUser mu) {
        String sql = "select userName ,age ,sex,titleImg from user6 where userId=?";
        Object[] param1 = { userId };
        ResultSet rs = dbu.select(sql, param1);
        try {
            while (rs.next()) {
                mu.setUserName(rs.getString("userName"));
                mu.setAge(rs.getInt("age"));
                mu.setSex(rs.getInt("sex"));
                mu.setTitleImg(rs.getInt("titleImg"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbu.close();
        }
    }

    // 通过userName查询userId
    public int selectUserId(String userName) {
        String sql = "select userId ,age ,sex from user6 where userName=?";
        Object[] param1 = { userName };
        ResultSet rs = dbu.select(sql, param1);
        int userId = -1;
        try {
            while (rs.next()) {
                userId = rs.getInt("userId");
            }
            return userId;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbu.close();
        }
        return userId;
    }

    // 用户登录
    public User loginCheck(String username, String password) {
        String sql = "select * from user6 where userName=? and userPwd=?";
        Object[] param = { username, password };
        ResultSet rs = dbu.select(sql, param);
        User user = null;
        try {
            while (rs.next()) {
                user = new User();
                user.setUserId(rs.getInt("userId"));
                user.setUserName(rs.getString("userName"));
                user.setUserPwd(rs.getString("userPwd"));
                user.setAge(rs.getInt("age"));
                user.setPwdCommand(rs.getString("pwdCommand"));
                user.setSex(rs.getInt("sex"));
            }
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            dbu.close();
        }
    }

    // 验证用户名是否存在
    public boolean checkUserExists(String userName) {

        String sql = "select count(*) from user6 where username=?";
        Object[] param = { userName };
        ResultSet rs = dbu.select(sql, param);
        int count = 0;
        try {
            while (rs.next()) {
                count = rs.getInt(1);
            }
            if (count > 0) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            dbu.close();
        }
    }

    // 添加用户
    public int AddUser(User user) {
        String sql = "insert into user6(userId,userName,userPwd,age,pwdCommand,sex,titleImg) values(id_a.nextval,?,?,?,?,?)";
        Object[] param = { user.getUserName(), user.getUserPwd(), user.getAge(), user.getPwdCommand(), user.getSex(),
                user.getTitleImg() };
        int count = dbu.update(sql, param);
        dbu.close();
        return count;
    }
}

Config.java

package com.auuzee.dbutil;

import java.io.IOException;
import java.util.Properties;

public class Config {

    private static Properties pro = new Properties();

    static {
        try {
            // 通过反射的方式加载资源文件
            // 只要资源文件和Config类在同一个路径下就能找到并加载到Properties对象中,以map的形式存放
            pro.load(Config.class.getResourceAsStream("db.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static final String DBURL = pro.getProperty("DBURL");
    public static final String DBIP = pro.getProperty("DBIP");
    public static final String DBPORT = pro.getProperty("DBPORT");
    public static final String DATABASE = pro.getProperty("DATABASE");
    public static final String DBUSER = pro.getProperty("DBUSER");
    public static final String DBPASS = pro.getProperty("DBPASS");
    public static final String DBDRIVER = pro.getProperty("DBDRIVER");
}

DBUtil.java

package com.auuzee.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {

    // 数据库连接字符串
    private String url = Config.DBURL + Config.DBIP + Config.DBPORT + Config.DATABASE;
    // 数据库连接用户名
    private String user = Config.DBUSER;
    // 数据库连接密码
    private String password = Config.DBPASS;

    private Connection con = null;
    private PreparedStatement pst = null;
    private Statement st = null;
    private ResultSet rs = null;

    // 获取连接
    private void getConn() {
        try {
            // 加载驱动
            Class.forName(Config.DBDRIVER);
            // 建立连接
            con = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * 共通查询方法 params:Strng sql:需要执行的SQL语句 Object[] param:需要替换占位符的参数数组
     * return:rs:执行查询得到的结果集
     */
    public ResultSet select(String sql, Object[] param) {
        // 调用共通方法获取连接
        getConn();
        try {
            // 创建Statement对象
            pst = con.prepareStatement(sql);
            // SQL占位符替换
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    pst.setObject(i + 1, param[i]);
                }
            }
            // 执行SQL
            rs = pst.executeQuery();
            return rs;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 共通更新方法 params:Strng sql:需要执行的SQL语句 Object[] param:需要替换占位符的参数数组
     * return:count:执行更新得到的影响行数
     */
    public int update(String sql, Object[] param) {
        // 调用共通方法获取连接
        getConn();
        try {
            // 创建Statement对象
            pst = con.prepareStatement(sql);
            // SQL占位符替换
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    pst.setObject(i + 1, param[i]);
                }
            }
            // 执行SQL
            int count = pst.executeUpdate();
            return count;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
    }

    /*
     * 共通批处理方法 params:String[] sql:需要执行的SQL语句数组 return:counts:执行批处理得到的影响行数数组
     */
    public int[] batch(String[] sql) {
        // 调用共通方法获取连接
        getConn();
        try {
            // 创建Statement对象
            st = con.createStatement();
            // 添加批处理SQL
            for (String s : sql) {
                st.addBatch(s);
            }
            // 执行批处理
            int[] counts = st.executeBatch();
            return counts;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    // 关闭资源
    public void close() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (pst != null) {
                pst.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

db.properties

#DBURL=jdbc:mysql://
#DBIP=localhost
#DBPORT=:3306
#DATABASE=/test
#DBUSER=root
#DBPASS=123456
#DBDRIVER=com.mysql.jdbc.Driver
DBURL=jdbc:oracle:thin:@
DBIP=localhost
DBPORT=:1521
DATABASE=:ORCL
DBUSER=system
DBPASS=123456
DBDRIVER=oracle.jdbc.driver.OracleDriver