JavaWeb结合七牛云存储搭建个人相册

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

JavaWeb结合七牛云存储搭建个人相册

、引言

1. 课程概述

相信很多人都知道网站一般会有很多图片,对于小型网站来说,图片放在网站服务器上不算什么,但当图片数量很大时,会造成服务器很臃肿,相应地对带宽要求也会提高,这就造成了成本的增加。其实现在已经流行云存储,我们可以把图片、大文件等放到第三方提供的云存储服务上,这会减少一部分成本。这门课程就介绍了JavaWeb结合七牛云存储来搭建个人相册服务。

2. 预备知识

掌握Servlet+JSP,能了解Bootstrap更好。

、Just Do It!

项目开始前,你需要有一个七牛云存储的标准用户账号,新建一个Bucket,知道你自己的Access Key和Secret Key。

 

1. 创建数据库

这里我们使用MySQL数据库,创建名称为photo的数据库:

 

create database photo DEFAULT CHARSET=utf8;

CREATE TABLE `image` (  
`id` int(11) NOT NULL AUTO_INCREMENT,  
`name` varchar(16) DEFAULT NULL,  
`url` varchar(255) DEFAULT NULL,  
`date` datetime DEFAULT NULL,  
`user_id` int(11) DEFAULT NULL,  
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `user` (  
`id` int(11) NOT NULL AUTO_INCREMENT,  
`username` varchar(16) DEFAULT NULL,  
`password` varchar(16) DEFAULT NULL,  
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


 

2. 创建JavaWeb项目

这里使用Eclipse创建一个名称为Photo的动态Web项目,加入Tomcat 7服务器,加入所需的jar包(源码中包含jar包),把Photo项目部署到Tomcat上。

3. 编写前端代码

前端使用Bootsrap,把css、fonts和js文件夹放到WebContent目录下。

创建index.jsp:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


  
    
    
    
    实验楼个人相册
    
    
  
  
    
        
            
                

实验楼个人相册

            
        
                                      注册成功             
        
                                用户名                                         
          
                       密码                                         
          
                                      登录             
                           注册             
                                                                          ×Close             用户注册                                                                     用户名                                                                                                    密码                                                                                                    重复密码                                                                                                                    取消             注册                                                             $(document).ready(function() {                //点击登录             $('#login').click(function() {                  //提交登录表单                 $.post('${pageContext.request.contextPath}' + '/UserAction?type=1',                 {                     username: $('#username').val(),                     password: $('#password').val()                 },                      function(data, status) {                        if (data == '1') {                         createPopOver('#username', 'right', '用户名不能为空', 'show');                     } else if (data == '2') {                         createPopOver('#password', 'right', '密码不能为空', 'show');                     } else if (data == '3') {                         createPopOver('#username', 'right', '用户名不存在', 'show');                     } else if (data == '4') {                         createPopOver('#password', 'right', '密码错误', 'show');                     } else if (data == 5) {                         location.href = '${pageContext.request.contextPath}' + '/home.jsp';                     }                 });             });                      //点击注册按钮             $('#register').click(function() {                     //提交注册表单                 $.post('${pageContext.request.contextPath}' + '/UserAction?type=2',                 {                     username: $('#reg_username').val(),                     password: $('#reg_password').val(),                     repassword: $('#reg_repassword').val()                 },                   function(data, status) {                      if (data == '1') {                         createPopOver('#reg_username', 'right', '不能为空', 'show');                     } else if (data == '2') {                         createPopOver('#reg_password', 'right', '不能为空', 'show');                     } else if (data == '3') {                         createPopOver('#reg_repassword', 'right', '不能为空', 'show');                     } else if (data == '4') {                         createPopOver('#reg_repassword', 'right', '密码不一致', 'show');                     } else if (data == '5') {                         createPopOver('#reg_username', 'right', '用户名已存在', 'show');                     } else if (data == '6') {                         $('#reg_username').val('');                         $('#reg_password').val('');                         $('#reg_repassword').val('');                         $('#myModal').modal('hide');                         $('#alert1').removeClass('hide');                         $('#form').css('margin-top', '0px');                     }                 });             });              //显示弹出框             function createPopOver(id, placement, content, action) {                 $(id).popover({                     placement: placement,                     content: content                 });                 $(id).popover(action);             }             //点击输入框时销毁弹出框             $('#username').click(function() {                 $('#username').popover('destroy');             });             $('#password').click(function() {                 $('#password').popover('destroy');             });             $('#reg_username').click(function() {                 $('#reg_username').popover('destroy');             });             $('#reg_password').click(function() {                 $('#reg_password').popover('destroy');             });             $('#reg_repassword').click(function() {                 $('#reg_repassword').popover('destroy');             });         });        


创建home.jsp:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


  
    
    
    
    ${user.username}的个人相册
    
    
  
  
    
        
        
            
                
                    ${user.username}   ${imageList.size()}张
                    
                      
                          操作
                      
                      
                        
  • 上传
  •                         
  • 删除
  •                         
  • 退出
  •                                                                                                                                                                                                                                                  " style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">                             ${image.name }                                                                                                                                                                         " style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">                             ${image.name }                                                                                                                                                                                 " style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">                         ${image.name }                                                                                                                                                                                               ×                                                                                                                          图片上传                                                                       名称                                                                                                    图片                                                                                                                      取消             上传                                                                                       确定删除吗?                                   取消             确定                                                                                       确定退出吗?                                   取消             确定                                                             $(document).ready(function() {             //点击图片             $('img').click(function() {                 $('#myModalLabel').html($(this).attr('name') + '   ' + $(this).attr('date') + '');                 $('#modal-content').html('');                 $('#myModal').modal('show');             });             //点击上传             $('#upload').click(function() {                if ($('#image_name').val() == '' || $('#image').val() == '') {                 } else {                     $('#form').attr('action', '${pageContext.request.contextPath}' + '/ImageAction?type=1');                     $('#form').attr('enctype', 'multipart/form-data');                     $('#form').attr('method', 'post');                     $('#form').submit();                 }             });                          //点击确定退出             $('#exit').click(function() {                 $.get('${pageContext.request.contextPath}' + '/UserAction?type=3', function(data, status) {                     location.href = '${pageContext.request.contextPath}' + '/index.jsp';                 });             });             //点击确定删除图片             $('#delete').click(function() {                 var ids = "";                 var urls = "";                 $('input[type=checkbox]:checked').each(function() {                     ids += $(this).val() + ',';                     urls += $(this).attr('url') + ',';                 });                  $.post('${pageContext.request.contextPath}' + '/ImageAction?type=2', {                     ids: ids,                     urls: urls                 },function(data, status) {                     $('#myModa3').modal('hide');                     location.href = '${pageContext.request.contextPath}' + '/home.jsp';                 });             });         });         


     

    4. 编写后台代码

    创建User类:

     

     * 用户类
     * @author www.shiyanlou.com
     *
     */
    @SuppressWarnings("serial")
    public class User implements Serializable { 
        private int id;    //用户ID
        private String username;    //用户名
        private String password;    //密码
        private List images;    //图片列表
    
        public User() {
        } 
        public User(int id, String username, String password, List images) { 
           this.id = id; 
           this.username = username; 
           this.password = password; 
           this.images = images;
        } 
     
        public User(String username, String password) { 
           this.username = username; 
           this.password = password;
        } 
      
        public User(int id) { 
           this.id = id;
        } 
    
        public List getImages() { 
           return images;
        } 
    
        public void setImages(List images) { 
           this.images = images;
        } 
    
        public int getId() { 
           return id;
        } 
    
        public void setId(int id) { 
           this.id = id;
        } 
    
        public String getUsername() { 
           return username;
        } 
    
        public void setUsername(String username) { 
           this.username = username;
        } 
    
        public String getPassword() { 
           return password;
        } 
    
        public void setPassword(String password) { 
           this.password = password;
        }
    
    }


    创建Image类:

     

    /**
     * 图片类
     * @author www.shiyanlou.com
     *
     */@SuppressWarnings("serial")
    public class Image implements Serializable { 
        private int id;    //图片ID
        private String name;    //图片名
        private String url;    //图片URL
        private Date date;    //上传时间
        private User user;    //所属用户
    
        public int getId() { 
           return id;
        } 
    
        public void setId(int id) { 
           this.id = id;
        } 
    
        public String getName() { 
           return name;
        } 
    
        public void setName(String name) { 
           this.name = name;
        } 
    
        public String getUrl() { 
           return url;
        } 
    
        public void setUrl(String url) { 
           this.url = url;
        } 
    
        public Date getDate() { 
           return date;
        }  
    
        public void setDate(Date date) {  
           this.date = date;
        } 
    
        public User getUser() { 
           return user;
        } 
    
        public void setUser(User user) { 
           this.user = user;
        }
    }


     

    创建数据库工具类:

     

    /**
     * 数据库工具类
     * @author www.shiyanlou.com
     *
     */public class DBUtils { 
        private static Connection connection = null; 
        private static PreparedStatement preparedStatement = null; 
        private static ResultSet resultSet = null; 
    
        //初始化
        static { 
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } 
     
        /**
         * 获取连接
         * @return
         */
        private static Connection getConnection() { 
            try {
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/photo?useUnicode=true&characterEncoding=UTF-8", "root", "root");
            } catch (SQLException e) {
                e.printStackTrace();
            }        return connection;
        } 
    
        /**
         * 关闭连接、预处理语句和结果集
         * @param connection
         * @param preparedStatement
         * @param resultSet
         */
        private static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) { 
            try { 
                if (resultSet != null) {
                    resultSet.close();
                    resultSet = null;
                } 
    
                if (preparedStatement != null) {
                    preparedStatement.close();
                    preparedStatement = null;
                }  
    
                if (connection != null) {
                    connection.close();
                    connection = null;
                }            
            } catch (Exception e) {
                e.printStackTrace();
            }
        } 
    
        /**
         * 查询数据库
         * @param sql SQL语句
         * @param parameters 参数
         * @return
         */
        public static ArrayList query(String sql, String[] parameters) {
            ArrayList list = new ArrayList(); 
            try {
                connection = getConnection();
                preparedStatement = connection.prepareStatement(sql); 
                for (int i = 0; i < parameters.length; i++) {
                    preparedStatement.setString(i + 1, parameters[i]);
                }
                resultSet = preparedStatement.executeQuery(); 
                int columnCount = resultSet.getMetaData().getColumnCount(); 
                while (resultSet.next()) {
                    Object[] objects = new Object[columnCount];  
                    for (int i = 0; i < columnCount; i++) {
                        objects[i] = resultSet.getObject(i + 1);
                    }
                    list.add(objects);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                close(connection, preparedStatement, resultSet);
            } 
            return list;
        } 
    
        /**
         * 更新数据库
         * @param sqls SQL语句数组
         * @param parameters 参数数组
         */
        public static void updates(String[] sqls, String[][] parameters) { 
            try {
                connection = getConnection();
                connection.setAutoCommit(false); 
                for (int i = 0; i < sqls.length; i++) {
                    preparedStatement = connection.prepareStatement(sqls[i]); 
                    for (int j = 0; j < parameters[i].length; j++) {
                        preparedStatement.setString(j + 1, parameters[i][j]);
                    }
                    preparedStatement.executeUpdate();
                }
                connection.commit();
            } catch (Exception e) { 
                try {
                    connection.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            } finally {
                close(connection, preparedStatement, resultSet);
            }
        }
    }


     

    创建文件工具类(使用了七牛云存储服务)

     

    /**
     * 图片工具类(使用七牛云存储服务)
     * @author www.shiyanlou.com
     *
     */
    public class FileUtils { 
        private static final String ACCESS_KEY = "你自己的Access Key"; 
        private static final String SECRET_KEY = "你自己的Secret Key"; 
        private static final String BUCKET_NAME = "创建的Bucket的名称"; 
    
        /**
         * 上传图片到七牛云存储
         * @param reader
         * @param fileName
         */
        public static void upload(InputStream reader, String fileName) {
            String uptoken; 
            try {
                Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
                PutPolicy putPolicy = new PutPolicy(BUCKET_NAME);
                uptoken = putPolicy.token(mac);
                IoApi.Put(uptoken, fileName, reader, null);
            } catch (AuthException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }    /**
         * 删除七牛云存储上的图片
         * @param key
         */
        public static void delete( String key) {
            Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
            RSClient client = new RSClient(mac);
            client.delete(BUCKET_NAME, key);
        }
    }


    创建用户服务类:

     

    /**
     * 用户服务类
     * @author www.shiyanlou.com
     *
     */
    public class UserService { 
        /**
         * 通过用户名获取用户
         * @param username 用户名
         * @return 用户
         */
        public User getUserByUsername(String username) {
            String sql = "select id, username, password from user where username = ?";
            String[] parameters = {username};
            List users = DBUtils.query(sql, parameters); 
            if (users.size() == 0) { 
                return null;
            } else {
                Object[] objects = users.get(0); 
                return objects == null ? null : new User(Integer.parseInt(objects[0].toString()), objects[1].toString(), objects[2].toString(), null);
            }
        } 
    
        /**
         * 添加用户
         * @param user 用户
         */
        public void addUser(User user) {
            String[] sqls = {"insert into user(username, password) values(?, ?)"};
            String[][] parameters = {{user.getUsername(), user.getPassword()}};
            DBUtils.updates(sqls, parameters);
        }
    }


     

    创建图片服务类:

     

    /**
     * 图片服务类
     * @author www.shiyanlou.com
     *
     */
    public class ImageService { 
        /**
         * 通过用户ID获取图片列表
         * @param userId 用户ID
         * @return 图片列表
         */
        public ArrayList getByUserId(int userId) {
            ArrayList images = new ArrayList();
            String sql = "select id, name, url, date, user_id from image where user_id = ? order by date desc";
            String[] parameters = {userId + ""};
            List imageList = DBUtils.query(sql, parameters); 
            for (Object[] objects : imageList) {
                Image image = new Image();
                image.setId(Integer.parseInt(objects[0].toString()));
                image.setName(objects[1].toString());
                image.setUrl(objects[2].toString());
                image.setDate((Date) objects[3]);
                image.setUser(new User(Integer.parseInt(objects[4].toString())));
                images.add(image);
            } 
            return images;
        } 
     
        /**
         * 上传图片
         * @param image 图片
         * @param inputStream 输入流
         */
        public void addImage(Image image, InputStream inputStream) {
            FileUtils.upload(inputStream, image.getUrl());
            String[] sqls = {"insert into image(name, url, date, user_id) values(?, ?, ?, ?)"};
            String[][] parameters = {{image.getName(), image.getUrl(), new SimpleDateFormat("yyyy-MM-dd HH:mm").format(image.getDate()), image.getUser().getId() + ""}};
            DBUtils.updates(sqls, parameters);
        } 
    
        /**
         * 通过图片ID数组和图片URL数组删除图片
         * @param ids 图片ID数组
         * @param urls 图片URL数组
         */
        public void delByIdsAndUrls(String ids, String urls) {
            String[] idArray = ids.split(",");
            String[] urlArray = urls.split(","); 
            if (!"".equals(idArray[0]) && !"".equals(urlArray[0])) {
                String[] sqls = new String[idArray.length];
                String[][] parameters = new String[idArray.length][1];            for (int i = 0; i < idArray.length; i++) {
                    FileUtils.delete(urlArray[i]);
                    sqls[i] = "delete from image where id = ?";
                    parameters[i][0] = idArray[i];
                }
                DBUtils.updates(sqls, parameters);
            }
        }
    }


     

    创建用户控制器类:

     

    /**
     * 用户控制器
     * @author www.shiyanlou.com
     *
     */
    @WebServlet(value = "/UserAction")
    public class UserAction extends HttpServlet { 
        private static final long serialVersionUID = 1L; 
     
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("Utf-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            UserService userService = new UserService();
            ImageService imageService = new ImageService();
    
            Integer type = Integer.valueOf(request.getParameter("type")); 
            if (type == 1) {    //用户登录
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String result = null;
                User user = null; 
                //验证用户是否有效
                if (username.isEmpty()) {
                    result = "1";
                } else if (password.isEmpty()) {
                    result = "2";
                } else if ((user = userService.getUserByUsername(username)) == null) {
                    result = "3";
                } else { 
                    if (!user.getPassword().equals(password)) {
                        result = "4";
                    } else {
                        request.getSession().setAttribute("user", user);
                        request.getSession().setAttribute("imageList", imageService.getByUserId(user.getId()));
                        result = "5";
                    }
                }
                out.print(result);
            } else if (type == 2) {    //用户注册
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String repassword = request.getParameter("repassword");
                String result = null; 
                //验证有效性
                if (username.isEmpty()) {
                    result = "1";
                } else if (password.isEmpty()) {
                    result = "2";
                } else if (repassword.isEmpty()) {
                    result = "3";
                } else if (!repassword.equals(password)) {
                    result = "4";
                } else if (userService.getUserByUsername(username) != null) {
                    result = "5";
                } else {
                    User user = new User(username, password); 
                    //添加用户
                    userService.addUser(user);
                    result = "6";
                }
                out.print(result);
            } else if (type == 3) {    //用户退出
                request.getSession().invalidate();
            }
        } 
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
            this.doGet(request, response);
        }
    
    }


    创建图片控制器类:

     

    /**
     * 图片控制器
     * @author www.shiyanlou.com
     *
     */
    @WebServlet(value = "/ImageAction")
    @MultipartConfig
    public class ImageAction extends HttpServlet { 
        private static final long serialVersionUID = 1L; 
     
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            Integer type = Integer.valueOf(request.getParameter("type"));
            ImageService imageService = new ImageService(); 
            if (type == 1) {    //上传图片
                String imageName = request.getParameter("image_name");
                Part image = request.getPart("image");
                Image img = new Image();
                img.setDate(new Date());
                img.setName(imageName);
                img.setUser((User) request.getSession().getAttribute("user"));
                img.setUrl(img.getUser().getUsername() + "/" + UUID.randomUUID());
                imageService.addImage(img, image.getInputStream());
                request.getSession().setAttribute("imageList", imageService.getByUserId(img.getUser().getId()));
                response.sendRedirect(request.getContextPath() + "/home.jsp");
            } else if (type == 2) {    //删除图片
                String ids = request.getParameter("ids");
                String urls = request.getParameter("urls");
                imageService.delByIdsAndUrls(ids, urls);
                request.getSession().setAttribute("imageList", imageService.getByUserId(((User) request.getSession().getAttribute("user")).getId()));
            }
        } 
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
            this.doGet(request, response);
        }
    
    }


     

    5. 发布

    把Photo部署到Tomcat上,启动服务器,访问http://127.0.0.1:8080/Photo

    6.项目截图

    图片1

    JavaWeb结合七牛云存储搭建个人相册_第1张图片

    图片2

    JavaWeb结合七牛云存储搭建个人相册_第2张图片

    图片3

    JavaWeb结合七牛云存储搭建个人相册_第3张图片

    图片4

    JavaWeb结合七牛云存储搭建个人相册_第4张图片

    图片5

    JavaWeb结合七牛云存储搭建个人相册_第5张图片

    图片6

    JavaWeb结合七牛云存储搭建个人相册_第6张图片

    图片7

    JavaWeb结合七牛云存储搭建个人相册_第7张图片

    图片8

    JavaWeb结合七牛云存储搭建个人相册_第8张图片

    图片9

    JavaWeb结合七牛云存储搭建个人相册_第9张图片


     

     

    详细代码内容或有不解请登录该项目课网站http://www.shiyanlou.com/courses/54

    项目课大赛三千元等你来拿~入围就有百元红包

    详情请戳:http://www.shiyanlou.com/huodong/projects.html

    JavaWeb结合七牛云存储搭建个人相册_第10张图片

    转载于:https://my.oschina.net/shiyanlou/blog/367304

    你可能感兴趣的:(JavaWeb结合七牛云存储搭建个人相册)