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

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

3.点击发表

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

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

主要用到的知识有:

图片的上传,session,JavaScript

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

代码随后上传

主页面

添加文字图片

点击发表后的页面

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

 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

send_bg.jpg

效果图:

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

jsp模仿QQ空间说说的发表的更多相关文章

  1. 模仿QQ空间 网页设计

    目的:1.通过模仿QQ空间,全自主写代码,熟悉网页设计的流程 2.熟练的掌握HTML.CSS.JS的应用 3.将在此过程中遇到的问题及其解决方法记录在此,以便取用. 开始: 一.登陆界面(index. ...

  2. Android 模仿QQ空间风格的 UI(转)

    本文内容 环境 演示模仿QQ空间风格的UI 虽然这个 UI 跟现在的QQ空间有点差别,但是也能学到很多东西. 下载 Demo 环境 Windows 7 64 位 Eclipse ADT V22.6.2 ...

  3. Android 模仿QQ空间风格的 UI

    本文内容 环境 演示模仿QQ空间风格的UI 虽然这个 UI 跟现在的QQ空间有点差别,但是也能学到很多东西. 下载 Demo 环境 Windows 7 64 位 Eclipse ADT V22.6.2 ...

  4. 模仿qq空间或朋友圈发布动态、评论动态、回复评论、删除动态或评论的功能(上)

      我们大部分人都发过动态,想必都知道发动态.回复评论.删除动态的整个过程,那么作为初学者,要模仿这些功能有点复杂的,最起码表的关系得弄清楚~~ 先把思路理一下: (1)用户登录,用session读取 ...

  5. Android模仿QQ空间图片上传——原理

    MainActivity.class package com.example.imagedemotext; import java.io.ByteArrayOutputStream; import j ...

  6. QQ空间分享功能(二)

    http://sns.z.qq.com/tools/share/demo_html.jsp  手机QQ空间分享功能接入指引: 1.请求地址: http://sns.z.qq.com/share 2.请 ...

  7. iOS开发UI篇—模仿ipad版QQ空间登录界面

    iOS开发UI篇—模仿ipad版QQ空间登录界面 一.实现和步骤 1.一般ipad项目在命名的时候可以加一个HD,标明为高清版 2.设置项目的文件结构,分为home和login两个部分 3.登陆界面的 ...

  8. php模拟用户自动在qq空间发表文章的方法

    我们这里是一个简单的利用php来模拟登录后再到QQ空间发送文章的一个简单的程序,有需要的朋友可以参考,或改进可以给我意见,代码如下: <?php //模拟get post请求函数 http:// ...

  9. mui开发app之多图压缩与上传(仿qq空间说说发表)

    欲实现效果图 提出需求点: 用户可自由添加删除替换多张图片,并且显示相应缩略图,限制为8张 用户可选择压缩图或直接上传原图功能 返回提醒用户会丢失填写的信息 下面一个个实现上述需求,从简单到复杂: 需 ...

随机推荐

  1. 产生NaN

    1.数学运算失败  数字+undefind=NaN 2.数据类型转化失败产生NaN isNaN()检查 是不是一个有效数字,是NaN 返回 ture  ,正常数字返回false.

  2. 【转】mysql 拖库写库用法

    mysqldump常用于MySQL数据库逻辑备份. 1.各种用法说明 A. 最简单的用法: mysqldump -uroot -pPassword [database name] > [dump ...

  3. gruntJs篇之connect+watch自动刷新

    grunt很强大,可以帮我我们解决很多繁琐的操作,虽然刚接触不久,但依然感受到其强大之处,这篇记录一下通过grunt.js实现事实刷新页面, 省去了编码 -> 保存 -> F5..F5.. ...

  4. iOS进阶_三方使用步骤

    一.配置环境(:后为在终端输入的命令) 打开终端 查看自己电脑的Ruby环境:gem sources -l 如果环境已经是淘宝镜像了,此时不需要再进行环境的修改. 如果不是,发送gem sources ...

  5. c++中的指针之指针在数组

    使用一维指针数组输出一维数组中的数 int array[]={1,2,3,4,5,6};        int *p; p=array;        for(int i=0;i<6;i++){ ...

  6. 【C++自绘控件】如何用GDI+来显示图片

    在我们制作一个应用软件的时候往往需要在窗口或控件中添加背景图.而图片不仅有BMP格式的,还有JPEG.PNG.TIFF.GIF等其它的格式.那么如何用jpg格式的图片来当背景呢? 这里用到了GDI+, ...

  7. hdu 4698 - Counting(思路)

    转:题意:给定一个二维平面,其中x取值为1-N,y取值为1-M,现给定K个点,问至少包括K个点中的一个的满足要求的<Xmin, Xmax, Ymin, Ymax>共有多少中取值情况.也就是 ...

  8. JAVA缓存技术

    介绍 JNotify:http://jnotify.sourceforge.net/,通过JNI技术,让Java代码可以实时的监控制定文件夹内文件的变动信息,支持Linux/Windows/MacOS ...

  9. 阿里云Linux安装软件镜像源

    阿里云Linux安装软件镜像源 阿里云是最近新出的一个镜像源.得益与阿里云的高速发展,这么大的需求,肯定会推出自己的镜像源.阿里云Linux安装镜像源地址:http://mirrors.aliyun. ...

  10. UML动态模型图简单介绍

    UML动态模型图描述了系统动态行为的各个方面,包括用例图.序列图.协作图.活动图和状态图.下面就每种图做一个简单介绍: 用例图 用例图描述系统外部的执行者与系统提供的用例之间的某种联系.所谓用例是指对 ...