(一)
这学期上了一们叫做J2EE的选修课,本以为很水,没想到这个课这么烦气,最后大实验是一个springmvc的电子相册,做了两个周,终于完事了,姑且把这一篇叫做(一)吧
粗略看了一下啊,两个人的实验报告,后台java代码差不多1500多行,实验报告37页。。。反正很烦气。。。开始正经事
根据老师给的样例和查阅了很多的资料,最终采用的方法是:将图片的相对路径存入数据库,然后在web运行时候,获取到服务器所在的目录,然后进行存取。
本来想把代码整个工程上传上来,但是想想又好像很low的样子,实在需要的,可以邮箱联系:ahuskyboy@gmail.com
如果发现代码有什么问题,也请不吝赐教,评论或者邮箱都ok的~~多谢啦多谢啦
一,数据库:
在数据库建好,然后后台jdbc和implement都写好以后,出现了一个问题:picture的第二个字段,我之前的命名是describe但是总是报错,每次执行到这一行都会出错,最后发现,describe是sql中的一个关键词。。。。好坑爹
二,后台数据处理:由于实验是springmvc的,所以下面分层进行说明
<M>
1,model层
package cn.edu.ouc.model; import java.io.File; public class Picture {
private String name; // 图片名称
private String describe; // 描述
private String user; // 创建人
private boolean visited; // 是否可查看
private int album; // 所属的相册
private String images;// 图片文件 public Picture(){}; public String getPicturePath() {
File file = new File("resource");
String apath = file.getAbsolutePath();
String path =apath.substring(0, apath.lastIndexOf(File.separator));
path = path.replace('\\', '/');
String picPath = path+"\\WebContent\\WEB-INF\\resource\\";
//System.out.println);
file.delete();
return picPath;
} public Picture(String name, String describe, boolean visited, int album,
String images, String user) {
super();
this.name = name;
this.describe = describe;
this.user = user;
this.visited = visited;
this.album = album;
this.images = images;
} public String getUser() {
return user;
} public void setUser(String user) {
this.user = user;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDescribe() {
return describe;
} public void setDescribe(String describe) {
this.describe = describe;
} public boolean isVisited() {
return visited;
} public void setVisit(boolean visited) {
this.visited = visited;
} public int getAlbum() {
return album;
} public void setAlbum(int album) {
this.album = album;
} public String getImages() {
return images;
} public void setImages(String images) {
this.images = images;
} }
picture.class
2,jdbc连接数据库
这个没什么需要注意的,只要是mysql和java连接,都是大同小异的
package cn.edu.ouc.jdbc; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class ConnectDB { public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/2017end";
public static final String USERNAME = "root";
public static final String PASSWORD = "123456"; // 注册数据库驱动
static {
try {
Class.forName(DRIVER_CLASS_NAME);
} catch (ClassNotFoundException e) {
System.out.println("注册失败!");
e.printStackTrace();
}
} // 获取连接
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
} // 关闭连接
public static void closeConn(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("关闭连接失败!");
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) throws SQLException {
System.out.println(ConnectDB.getConn());
} }
ConnectDB.class
3,dao包(根据函数名应该大概知道什么意思吧~)
其实也是interface接口类
package cn.edu.ouc.dao; import java.util.ArrayList;
import java.util.List; import cn.edu.ouc.model.Picture; public interface PictureOperationDao {
public boolean add(Picture picture); public boolean deleteOnePicture(String name,int album); public boolean deleteByAlbum(int id); public boolean update(Picture picture); public ArrayList<Picture> getPicturesOfOneAlbum(int album); public List<Picture> getAllPirctures(); public List<Picture> getVisitedPictures(); Picture getOnePicture(String name, int album); }
PictureOperationDao.class
4,implement包
对接口进行实现的包
这里面尤其需要主义的是各种sql代码,例如:
String sql = "update picture set name = '" + name
+ "',description = '" + describe + "',isvisited = " + isVisit
+ ",album = " + album + ",source = '"+images +"',user = '"+user +"' where name = '"
+name +"'and album = "+album;
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
一定注意sql中各种单引号 ‘ 单引号只需要在数据库中为char和varchar的需要,int不需要,但是不能漏掉,我写代码过程中漏掉好多次。。。
package cn.edu.ouc.dao.impl; import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import com.mysql.jdbc.PreparedStatement; import cn.edu.ouc.dao.AlbumOperationDao;
import cn.edu.ouc.dao.PictureOperationDao;
import cn.edu.ouc.jdbc.ConnectDB;
import cn.edu.ouc.model.Album;
import cn.edu.ouc.model.Picture; public class PictureOperationDaoImpl implements PictureOperationDao { String name; // 图片名称
String describe; // 描述
String user; // 创建人
int isVisit; // 是否可查看
int album; // 所属的相册
String images;// 图片文件
AlbumOperationDao albumDao = new AlbumOperationDaoImpl(); @Override
public boolean add(Picture picture) {
// TODO Auto-generated method stub
name = picture.getName();
describe = picture.getDescribe();
user = picture.getUser();
if (picture.isVisited()) {
isVisit = 1;
} else {
isVisit = 0;
}
album = picture.getAlbum();
images = picture.getImages(); Album oneAlbum = albumDao.getAlbum(album); Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "insert into picture(name,description,isvisited,album,source,user) values(?,?,?,?,?,?)";
conn = ConnectDB.getConn();
ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, describe);
ps.setInt(3, isVisit);
ps.setInt(4, album);
ps.setString(5, images);
ps.setString(6, user);
if (ps.executeUpdate() > 0) {
oneAlbum.setCountPic((oneAlbum.getCountPic() + 1));
if (albumDao.update(oneAlbum)) {
System.out.println("插入成功");
return true;
} } else {
System.out.println("插入失败");
return false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} return false;
} @Override
public boolean deleteOnePicture(String name,int albumId) {
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "delete from picture where name = '" + name + "' and album = " +albumId;
conn = ConnectDB.getConn();
ps = (PreparedStatement) conn.prepareStatement(sql); Album oneAlbum = albumDao.getAlbum(album); if (ps.executeUpdate() > 0) { oneAlbum.setCountPic((oneAlbum.getCountPic() - 1));
if (albumDao.update(oneAlbum)) {
System.out.println("删除成功");
return true;
} else {
System.out.println("删除失败");
return false;
} } else {
System.out.println("删除失败");
return false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return false; } @Override
public boolean update(Picture picture) {
// TODO Auto-generated method stub
name = picture.getName();
describe = picture.getDescribe();
user = picture.getUser();
if (picture.isVisited()) {
isVisit = 1;
} else {
isVisit = 0;
}
album = picture.getAlbum();
images = picture.getImages(); Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "update picture set name = '" + name
+ "',description = '" + describe + "',isvisited = " + isVisit
+ ",album = " + album + ",source = '"+images +"',user = '"+user +"' where name = '"
+name +"'and album = "+album;
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
if (ps.executeUpdate() > 0) {
System.out.println("更新成功");
return true;
} else {
System.out.println("更新失败");
return false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return false;
} @Override
public ArrayList<Picture> getPicturesOfOneAlbum(int albumNum) {
// TODO Auto-generated method stub ArrayList<Picture> result = new ArrayList<Picture>();
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "select * from picture where album = "+albumNum;
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
boolean visited;
name = rs.getString(1);
describe = rs.getString(2);
isVisit = rs.getInt(3);
album = rs.getInt(4);
images = rs.getString(5);
user = rs.getString(6);
if (isVisit == 1) {
visited = true;
} else {
visited = false;
}
Picture picture = new Picture(name, describe, visited, album,images, user);
result.add(picture);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} return result;
} @Override
public List<Picture> getAllPirctures() {
// TODO Auto-generated method stub
ArrayList<Picture> result = new ArrayList<Picture>();
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "select * from picture";
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
boolean visited;
name = rs.getString(1);
describe = rs.getString(2);
isVisit = rs.getInt(3);
album = rs.getInt(4);
images = rs.getString(5);
user = rs.getString(6); if (isVisit == 1) {
visited = true;
} else {
visited = false;
}
Picture picture = new Picture(name, describe, visited, album,
images, user);
result.add(picture);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} return result;
} @Override
public boolean deleteByAlbum(int id) {
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "delete from picture where album = " + id;
conn = ConnectDB.getConn();
ps = (PreparedStatement) conn.prepareStatement(sql);
if (ps.executeUpdate() > 0) {
System.out.println("删除成功");
return true;
} else {
System.out.println("删除失败");
return false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return false;
} @Override
public Picture getOnePicture(String name, int album) {
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "select * from picture where name = '"+name+"'and album = "+album;
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
boolean visited;
name = rs.getString(1);
describe = rs.getString(2);
isVisit = rs.getInt(3);
album = rs.getInt(4);
images = rs.getString(5);
user = rs.getString(6); if (isVisit == 1) {
visited = true;
} else {
visited = false;
}
Picture picture = new Picture(name, describe, visited, album,
images, user); return picture;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} return null;
}
@Override
public List<Picture> getVisitedPictures() {
// TODO Auto-generated method stub
ArrayList<Picture> result = new ArrayList<Picture>();
Connection conn = null;
PreparedStatement ps = null;
try {
String sql = "select * from picture where isvisited = '1'";
conn = ConnectDB.getConn();// 获得连接
ps = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
boolean visited;
name = rs.getString(1);
describe = rs.getString(2);
isVisit = rs.getInt(3);
album = rs.getInt(4);
images = rs.getString(5);
user = rs.getString(6); if (isVisit == 1) {
visited = true;
} else {
visited = false;
}
Picture picture = new Picture(name, describe, visited, album,
images, user);
result.add(picture);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
ConnectDB.closeConn(conn);
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
} return result;
} }
PictureOperationDaoImpl.class
implement文件需要注意在import包时候,要加sql.....开头的,不要加mysql的
<V>
5,这里写了一个简单的jsp(其实是小组另一位同学写的啦)
好像是在菜鸟扒的吧。。哈哈哈,我也不懂
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<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>AddPic</title> <link
href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script
src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> </head>
<body> <div class="container-fluid"> <div class="col-md-12 column">
<form:form class="form-horizontal" commandName="picture"
action="${pageContext.request.contextPath}/save_Picture"
method="post" enctype="multipart/form-data">
<form class="form-horizontal"> <div class="form-group">
<label for="PictureName">PictureName</label>
<form:input class="form-control" id="name" path="name" />
</div>
<div class="form-group">
<label for="Picturedescribe">PicturDescribe</label>
<form:input class="form-control" id="describe" path="describe" />
</div> <div class="form-group">
<label for="user">user</label>
<form:input class="form-control" id="user" path="user" />
</div> <div class="form-group">
<label for="album">album</label>
<form:input class="form-control" id="album" path="album" />
</div> <div class="form-group">
<label for="exampleInputFile">File input</label> <input
class="form-control" name="picture" type="file" /> <input
class="form-control" name="image" type="hidden" value="default" />
</div> <div>
<input type="radio" name="isvisited" value="1">isVisited <input
type="radio" name="isvisited" value="0">unVisited
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</form:form>
</div> </div> <script src="https://code.jquery.com/jquery.js"></script>
<script
src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
AddPicture.jsp
其实这个就是利用jsp中的一个表单向后台传数据,注意的是,一定要把model类和jsp中对应起来,还有个各类的属性名
我也不很懂这些代码,不多说,会说错
因为这个jsp中实现了文件上传的功能,需要在springmvc-config中配置!!!!
然后添加一个包:
<!-- fileUpload Support -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!--max size: 10M-->
<property name="maxUploadSize" value="10485760"/>
</bean>
<C>
6,后台controller类
上面的代码其实都是大同小异的所以折叠起来,大家想看就看看吧,下面这一小段是最折磨我的。。。
由于这个controller中有很多控制,我只把其中的一部分拿出来
可以看到,我们利用HttpServletRequest 可以获取到后台的文件,然后转化成MultipartFile,然后将这个MultipartFile 存入本地(或者说服务器)
@Controller
public class PictureController { private PictureOperationDao PictureOp = new PictureOperationDaoImpl();
@RequestMapping(value = "/save_Picture")
public String SavePicture(HttpServletRequest request,
@ModelAttribute Picture picture) {
// 转型为MultipartHttpRequest(图片文件需要)
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile image = multipartRequest.getFile("picture");
// 图片名字
//利用这一句代码,可以获取到服务器所在的那个文件,由于我用的就是本地的Tomcat,在打印出这个路径之后是这样子的:
//F:/study/SomeCodes/JavaEEWorkplace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/2017End0629
File imageFile = new File(request.getServletContext()
.getRealPath(""));
String filepath = imageFile.toString();
System.out.println(filepath);
// 定义一个数组,用于保存可上传的文件类型
int visited = Integer.parseInt(request.getParameter("isvisited"));
if (visited == 1) {
picture.setVisit(true);
} else {
picture.setVisit(false);
} ArrayList<String> fileTypes = new ArrayList<String>();
fileTypes.add("jpg");
fileTypes.add("jpeg");
fileTypes.add("png");
fileTypes.add("gif");
// 保存图片
String imgUrl = null;
if (!(image.getOriginalFilename() == null || "".equals(image
.getOriginalFilename()))) {
File img = ImgManager.saveFile(image, fileTypes,filepath, "resource",
"image");
//下面这一句,也就是我说的相对路径、这个路径是不完整的,下面在显示照片时候会说明
imgUrl = "/resource/image/"+image.getOriginalFilename();
//imgUrl = img.toString();
}
//System.out.println(imgUrl);
// System.out.println(picture.getName());
PictureOperationDao pictureOperationDao = new PictureOperationDaoImpl();
imgUrl = imgUrl.replace('\\', '/');
picture.setImages(imgUrl);
if (pictureOperationDao.add(picture)) {
System.out.println("图片添加成功");
return "redirect:/list_Album";
}
System.out.println("图片添加失败");
return "redirect:/list_Album";
}
}
7,在显示照片时候:
同样的,我们首先通过jdbc获取到相对路径,然后通过遍历list表的方式,model中的路径加以修改:
首先获取到服务器地址,然后将这个地址与相对地址相加,就可以得到实际的地址~~~~
@RequestMapping(value = "/show_Pic/{id}")
public String ShowPicture(HttpServletRequest request,Model model, @PathVariable int id,
HttpSession session) {
File imageFile = new File(request.getServletContext()
.getRealPath(""));
String tomcatPath = imageFile.toString();
ArrayList<Picture> Pictures = PictureOp.getPicturesOfOneAlbum(id);
for (int i = 0; i < Pictures.size(); i++) {
String iPath = Pictures.get(i).getImages();
Pictures.get(i).setImages(tomcatPath+iPath);
}
model.addAttribute("Pictured", Pictures);
session.setAttribute("SessionAlbumID", id);
return "PictureList";
}
最后通过jsp的相关代码可以实现展示~~~~
就这样吧