您的位置:首页 > 编程语言 > Java开发

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

2015-01-17 17:55 423 查看
[align=center]JavaWeb结合七牛云存储搭建个人相册服务[/align]

一、引言
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"%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>实验楼个人相册</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 text-center">
<h2>实验楼个人相册</h2>
</div>
</div>
<div class="row">
<div id="alert1"  class="alert alert-success fade in text-center col-xs-2 col-xs-offset-5 hide">
<strong>注册成功</strong>
</div>
</div>
<form id="form" class="form-horizontal" role="form" style="margin-top: 73px;">
<div class="form-group"  >
<label for="username" class="col-xs-2 control-label col-sm-offset-3" >用户名</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="username" rel="tooltip"/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-xs-2 control-label col-sm-offset-3">密码</label>
<div class="col-xs-2">
<input type="password" class="form-control" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-xs-1">
<button type="button" class="btn btn-success" id="login">登录</button>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal">注册</button>
</div>
</div>
</form>
</div>

<!-- 注册对话框 begin -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">用户注册</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group"  >
<label for="reg_username" class="col-xs-2 control-label" >用户名</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="reg_username"/>
</div>
</div>
<div class="form-group">
<label for="reg_password" class="col-xs-2 control-label">密码</label>
<div class="col-xs-4">
<input type="password" class="form-control" id="reg_password"/>
</div>
</div>
<div class="form-group">
<label for="reg_repassword" class="col-xs-2 control-label">重复密码</label>
<div class="col-xs-4">
<input type="password" class="form-control" id="reg_repassword"/>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="register">注册</button>
</div>
</div>
</div>
</div>
<!-- 注册对话框 end -->

<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(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');
});
});
</script>
</body>
</html>


创建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" %>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${user.username}的个人相册</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<!-- 首部 start -->
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<h3 class="page-header">
${user.username}   <small>共<span class="badge">${imageList.size()}</span>张</small>
<div class="btn-group pull-right">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
操作<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" data-toggle="modal" data-target="#myModa2">上传</a></li>
<li><a href="#" data-toggle="modal" data-target="#myModa3">删除</a></li>
<li><a href="#" data-toggle="modal" data-target="#myModa4">退出</a></li>
</ul>
</div>
</h3>
</div>
</div>
<!-- 首部 end -->

<!-- 显示图片列表 -->
<c:forEach items="${imageList}" varStatus="status" var="image">
<c:choose>
<c:when test="${status.first or status.index % 4 eq 0}">
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}"/>${image.name }
</a>
</div>
</c:when>
<c:when test="${status.index % 4 eq 3 and not status.last }">
<div class="col-xs-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}" />${image.name }
</a>
</div>
</div>
</c:when>
<c:otherwise>
<div class="col-xs-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}"/>${image.name }
</a>
</div>
</c:otherwise>
</c:choose>
<c:if test="${status.last}">
</div>
</c:if>
</c:forEach>
<!-- 显示图片列表 end -->
</div>

<!-- 显示图片对话框 start -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"></h4>
</div>
<div class="modal-body" id="modal-content">
</div>
</div>
</div>
</div>
<!-- 显示图片对话框 end -->

<!-- 上传图片对话框 start -->
<div class="modal fade" id="myModa2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe2">图片上传</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" id="form">
<div class="form-group"  >
<label for="image_name" class="col-xs-2 control-label" >名称</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="image_name" name="image_name"/>
</div>
</div>
<div class="form-group">
<label for="image" class="col-xs-2 control-label">图片</label>
<div class="col-xs-4">
<input type="file" id="image" name="image"/>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="upload">上传</button>
</div>
</div>
</div>
</div>
<!-- 上传图片对话框 end -->

<!-- 删除图片对话框 start -->
<div class="modal fade" id="myModa3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe3">确定删除吗?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" id="delete">确定</button>
</div>
</div>
</div>
</div>
<!-- 删除图片对话框 end -->

<!-- 退出对话框 start -->
<div class="modal fade" id="myModa4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe4">确定退出吗?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" id="exit">确定</button>
</div>
</div>
</div>
</div>
<!-- 退出对话框 end -->

<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//点击图片
$('img').click(function() {
$('#myModalLabel').html($(this).attr('name') + '   <small>' + $(this).attr('date') + '</small>');
$('#modal-content').html('<img class=\'img-responsive\' src=\'' + $(this).attr('src') + '\'/>');
$('#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';
});
});
});
</script>
</body>
</html>


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<Image> images;    //图片列表

public User() {
}

public User(int id, String username, String password, List<Image> 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<Image> getImages() {
return images;
}

public void setImages(List<Image> 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<Object[]> query(String sql, String[] parameters) {
ArrayList<Object[]> list = new ArrayList<Object[]>();
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<Object[]> 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<Image> getByUserId(int userId) {
ArrayList<Image> images = new ArrayList<Image>();
String sql = "select id, name, url, date, user_id from image where user_id = ? order by date desc";
String[] parameters = {userId + ""};
List<Object[]> 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



图片2



图片3



图片4



图片5



图片6



图片7



图片8



图片9



如果有不懂和疑问欢迎登陆实验楼官方网站,http://www.shiyanlou.com/courses/

项目课大赛正在火热报名中,欢迎参加,一等奖三千元,入围就有百元红包!详情请戳http://www.shiyanlou.com/huodong/projects.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: