(一)
这学期上了一们叫做J2EE的选修课,本以为很水,没想到这个课这么烦气,最后大实验是一个springmvc的电子相册,做了两个周,终于完事了,姑且把这一篇叫做(一)吧
粗略看了一下啊,两个人的实验报告,后台java代码差不多1500多行,实验报告37页。。。反正很烦气。。。开始正经事
根据老师给的样例和查阅了很多的资料,最终采用的方法是:将图片的相对路径存入数据库,然后在web运行时候,获取到服务器所在的目录,然后进行存取。
本来想把代码整个工程上传上来,但是想想又好像很low的样子,实在需要的,可以邮箱联系:ahuskyboy@gmail.com
如果发现代码有什么问题,也请不吝赐教,评论或者邮箱都ok的~~多谢啦多谢啦
一,数据库:
在数据库建好,然后后台jdbc和implement都写好以后,出现了一个问题:picture的第二个字段,我之前的命名是describe但是总是报错,每次执行到这一行都会出错,最后发现,describe是sql中的一个关键词。。。。好坑爹
二,后台数据处理:由于实验是springmvc的,所以下面分层进行说明
<M>
1,model层
1 package cn.edu.ouc.model; 2 3 import java.io.File; 4 5 6 public class Picture { 7 private String name; // 图片名称 8 private String describe; // 描述 9 private String user; // 创建人 10 private boolean visited; // 是否可查看 11 private int album; // 所属的相册 12 private String images;// 图片文件 13 14 public Picture(){}; 15 16 public String getPicturePath() { 17 File file = new File("resource"); 18 String apath = file.getAbsolutePath(); 19 String path =apath.substring(0, apath.lastIndexOf(File.separator)); 20 path = path.replace('\\', '/'); 21 String picPath = path+"\\WebContent\\WEB-INF\\resource\\"; 22 //System.out.println); 23 file.delete(); 24 return picPath; 25 } 26 27 public Picture(String name, String describe, boolean visited, int album, 28 String images, String user) { 29 super(); 30 this.name = name; 31 this.describe = describe; 32 this.user = user; 33 this.visited = visited; 34 this.album = album; 35 this.images = images; 36 } 37 38 public String getUser() { 39 return user; 40 } 41 42 public void setUser(String user) { 43 this.user = user; 44 } 45 46 public String getName() { 47 return name; 48 } 49 50 public void setName(String name) { 51 this.name = name; 52 } 53 54 public String getDescribe() { 55 return describe; 56 } 57 58 public void setDescribe(String describe) { 59 this.describe = describe; 60 } 61 62 public boolean isVisited() { 63 return visited; 64 } 65 66 public void setVisit(boolean visited) { 67 this.visited = visited; 68 } 69 70 public int getAlbum() { 71 return album; 72 } 73 74 public void setAlbum(int album) { 75 this.album = album; 76 } 77 78 public String getImages() { 79 return images; 80 } 81 82 public void setImages(String images) { 83 this.images = images; 84 } 85 86 }
2,jdbc连接数据库
这个没什么需要注意的,只要是mysql和java连接,都是大同小异的
1 package cn.edu.ouc.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 public class ConnectDB { 8 9 public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; 10 public static final String URL = "jdbc:mysql://localhost:3306/2017end"; 11 public static final String USERNAME = "root"; 12 public static final String PASSWORD = "123456"; 13 14 // 注册数据库驱动 15 static { 16 try { 17 Class.forName(DRIVER_CLASS_NAME); 18 } catch (ClassNotFoundException e) { 19 System.out.println("注册失败!"); 20 e.printStackTrace(); 21 } 22 } 23 24 // 获取连接 25 public static Connection getConn() throws SQLException { 26 return DriverManager.getConnection(URL, USERNAME, PASSWORD); 27 } 28 29 // 关闭连接 30 public static void closeConn(Connection conn) { 31 if (null != conn) { 32 try { 33 conn.close(); 34 } catch (SQLException e) { 35 System.out.println("关闭连接失败!"); 36 e.printStackTrace(); 37 } 38 } 39 } 40 //测试 41 public static void main(String[] args) throws SQLException { 42 System.out.println(ConnectDB.getConn()); 43 } 44 45 46 }
3,dao包(根据函数名应该大概知道什么意思吧~)
其实也是interface接口类
1 package cn.edu.ouc.dao; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import cn.edu.ouc.model.Picture; 7 8 public interface PictureOperationDao { 9 public boolean add(Picture picture); 10 11 public boolean deleteOnePicture(String name,int album); 12 13 public boolean deleteByAlbum(int id); 14 15 public boolean update(Picture picture); 16 17 public ArrayList<Picture> getPicturesOfOneAlbum(int album); 18 19 public List<Picture> getAllPirctures(); 20 21 public List<Picture> getVisitedPictures(); 22 23 Picture getOnePicture(String name, int album); 24 25 26 }
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不需要,但是不能漏掉,我写代码过程中漏掉好多次。。。
1 package cn.edu.ouc.dao.impl; 2 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import com.mysql.jdbc.PreparedStatement; 9 10 import cn.edu.ouc.dao.AlbumOperationDao; 11 import cn.edu.ouc.dao.PictureOperationDao; 12 import cn.edu.ouc.jdbc.ConnectDB; 13 import cn.edu.ouc.model.Album; 14 import cn.edu.ouc.model.Picture; 15 16 public class PictureOperationDaoImpl implements PictureOperationDao { 17 18 String name; // 图片名称 19 String describe; // 描述 20 String user; // 创建人 21 int isVisit; // 是否可查看 22 int album; // 所属的相册 23 String images;// 图片文件 24 AlbumOperationDao albumDao = new AlbumOperationDaoImpl(); 25 26 @Override 27 public boolean add(Picture picture) { 28 // TODO Auto-generated method stub 29 name = picture.getName(); 30 describe = picture.getDescribe(); 31 user = picture.getUser(); 32 if (picture.isVisited()) { 33 isVisit = 1; 34 } else { 35 isVisit = 0; 36 } 37 album = picture.getAlbum(); 38 images = picture.getImages(); 39 40 Album oneAlbum = albumDao.getAlbum(album); 41 42 Connection conn = null; 43 PreparedStatement ps = null; 44 try { 45 String sql = "insert into picture(name,description,isvisited,album,source,user) values(?,?,?,?,?,?)"; 46 conn = ConnectDB.getConn(); 47 ps = (PreparedStatement) conn.prepareStatement(sql); 48 ps.setString(1, name); 49 ps.setString(2, describe); 50 ps.setInt(3, isVisit); 51 ps.setInt(4, album); 52 ps.setString(5, images); 53 ps.setString(6, user); 54 if (ps.executeUpdate() > 0) { 55 oneAlbum.setCountPic((oneAlbum.getCountPic() + 1)); 56 if (albumDao.update(oneAlbum)) { 57 System.out.println("插入成功"); 58 return true; 59 } 60 61 } else { 62 System.out.println("插入失败"); 63 return false; 64 } 65 } catch (Exception e) { 66 // TODO: handle exception 67 e.printStackTrace(); 68 } finally { 69 ConnectDB.closeConn(conn); 70 if (ps != null) { 71 try { 72 ps.close(); 73 } catch (Exception e2) { 74 // TODO: handle exception 75 e2.printStackTrace(); 76 } 77 } 78 } 79 80 return false; 81 } 82 83 @Override 84 public boolean deleteOnePicture(String name,int albumId) { 85 // TODO Auto-generated method stub 86 Connection conn = null; 87 PreparedStatement ps = null; 88 try { 89 String sql = "delete from picture where name = '" + name + "' and album = " +albumId; 90 conn = ConnectDB.getConn(); 91 ps = (PreparedStatement) conn.prepareStatement(sql); 92 93 Album oneAlbum = albumDao.getAlbum(album); 94 95 if (ps.executeUpdate() > 0) { 96 97 oneAlbum.setCountPic((oneAlbum.getCountPic() - 1)); 98 if (albumDao.update(oneAlbum)) { 99 System.out.println("删除成功"); 100 return true; 101 } else { 102 System.out.println("删除失败"); 103 return false; 104 } 105 106 } else { 107 System.out.println("删除失败"); 108 return false; 109 } 110 } catch (Exception e) { 111 // TODO: handle exception 112 e.printStackTrace(); 113 } finally { 114 ConnectDB.closeConn(conn); 115 if (ps != null) { 116 try { 117 ps.close(); 118 } catch (Exception e2) { 119 // TODO: handle exception 120 e2.printStackTrace(); 121 } 122 } 123 } 124 return false; 125 126 } 127 128 @Override 129 public boolean update(Picture picture) { 130 // TODO Auto-generated method stub 131 name = picture.getName(); 132 describe = picture.getDescribe(); 133 user = picture.getUser(); 134 if (picture.isVisited()) { 135 isVisit = 1; 136 } else { 137 isVisit = 0; 138 } 139 album = picture.getAlbum(); 140 images = picture.getImages(); 141 142 Connection conn = null; 143 PreparedStatement ps = null; 144 try { 145 String sql = "update picture set name = '" + name 146 + "',description = '" + describe + "',isvisited = " + isVisit 147 + ",album = " + album + ",source = '"+images +"',user = '"+user +"' where name = '" 148 +name +"'and album = "+album; 149 conn = ConnectDB.getConn();// 获得连接 150 ps = (PreparedStatement) conn.prepareStatement(sql); 151 if (ps.executeUpdate() > 0) { 152 System.out.println("更新成功"); 153 return true; 154 } else { 155 System.out.println("更新失败"); 156 return false; 157 } 158 } catch (Exception e) { 159 // TODO: handle exception 160 e.printStackTrace(); 161 } finally { 162 ConnectDB.closeConn(conn); 163 if (ps != null) { 164 try { 165 ps.close(); 166 } catch (Exception e2) { 167 // TODO: handle exception 168 e2.printStackTrace(); 169 } 170 } 171 } 172 return false; 173 } 174 175 @Override 176 public ArrayList<Picture> getPicturesOfOneAlbum(int albumNum) { 177 // TODO Auto-generated method stub 178 179 ArrayList<Picture> result = new ArrayList<Picture>(); 180 Connection conn = null; 181 PreparedStatement ps = null; 182 try { 183 String sql = "select * from picture where album = "+albumNum; 184 conn = ConnectDB.getConn();// 获得连接 185 ps = (PreparedStatement) conn.prepareStatement(sql); 186 ResultSet rs = ps.executeQuery(); 187 while (rs.next()) { 188 boolean visited; 189 name = rs.getString(1); 190 describe = rs.getString(2); 191 isVisit = rs.getInt(3); 192 album = rs.getInt(4); 193 images = rs.getString(5); 194 user = rs.getString(6); 195 if (isVisit == 1) { 196 visited = true; 197 } else { 198 visited = false; 199 } 200 Picture picture = new Picture(name, describe, visited, album,images, user); 201 result.add(picture); 202 } 203 } catch (Exception e) { 204 // TODO: handle exception 205 e.printStackTrace(); 206 } finally { 207 ConnectDB.closeConn(conn); 208 if (ps != null) { 209 try { 210 ps.close(); 211 } catch (Exception e2) { 212 // TODO: handle exception 213 e2.printStackTrace(); 214 } 215 } 216 } 217 218 return result; 219 } 220 221 @Override 222 public List<Picture> getAllPirctures() { 223 // TODO Auto-generated method stub 224 ArrayList<Picture> result = new ArrayList<Picture>(); 225 Connection conn = null; 226 PreparedStatement ps = null; 227 try { 228 String sql = "select * from picture"; 229 conn = ConnectDB.getConn();// 获得连接 230 ps = (PreparedStatement) conn.prepareStatement(sql); 231 ResultSet rs = ps.executeQuery(); 232 while (rs.next()) { 233 boolean visited; 234 name = rs.getString(1); 235 describe = rs.getString(2); 236 isVisit = rs.getInt(3); 237 album = rs.getInt(4); 238 images = rs.getString(5); 239 user = rs.getString(6); 240 241 if (isVisit == 1) { 242 visited = true; 243 } else { 244 visited = false; 245 } 246 Picture picture = new Picture(name, describe, visited, album, 247 images, user); 248 result.add(picture); 249 } 250 } catch (Exception e) { 251 // TODO: handle exception 252 e.printStackTrace(); 253 } finally { 254 ConnectDB.closeConn(conn); 255 if (ps != null) { 256 try { 257 ps.close(); 258 } catch (Exception e2) { 259 // TODO: handle exception 260 e2.printStackTrace(); 261 } 262 } 263 } 264 265 return result; 266 } 267 268 @Override 269 public boolean deleteByAlbum(int id) { 270 // TODO Auto-generated method stub 271 Connection conn = null; 272 PreparedStatement ps = null; 273 try { 274 String sql = "delete from picture where album = " + id; 275 conn = ConnectDB.getConn(); 276 ps = (PreparedStatement) conn.prepareStatement(sql); 277 if (ps.executeUpdate() > 0) { 278 System.out.println("删除成功"); 279 return true; 280 } else { 281 System.out.println("删除失败"); 282 return false; 283 } 284 } catch (Exception e) { 285 // TODO: handle exception 286 e.printStackTrace(); 287 } finally { 288 ConnectDB.closeConn(conn); 289 if (ps != null) { 290 try { 291 ps.close(); 292 } catch (Exception e2) { 293 // TODO: handle exception 294 e2.printStackTrace(); 295 } 296 } 297 } 298 return false; 299 } 300 301 @Override 302 public Picture getOnePicture(String name, int album) { 303 // TODO Auto-generated method stub 304 Connection conn = null; 305 PreparedStatement ps = null; 306 try { 307 String sql = "select * from picture where name = '"+name+"'and album = "+album; 308 conn = ConnectDB.getConn();// 获得连接 309 ps = (PreparedStatement) conn.prepareStatement(sql); 310 ResultSet rs = ps.executeQuery(); 311 while (rs.next()) { 312 boolean visited; 313 name = rs.getString(1); 314 describe = rs.getString(2); 315 isVisit = rs.getInt(3); 316 album = rs.getInt(4); 317 images = rs.getString(5); 318 user = rs.getString(6); 319 320 if (isVisit == 1) { 321 visited = true; 322 } else { 323 visited = false; 324 } 325 Picture picture = new Picture(name, describe, visited, album, 326 images, user); 327 328 return picture; 329 } 330 } catch (Exception e) { 331 // TODO: handle exception 332 e.printStackTrace(); 333 } finally { 334 ConnectDB.closeConn(conn); 335 if (ps != null) { 336 try { 337 ps.close(); 338 } catch (Exception e2) { 339 // TODO: handle exception 340 e2.printStackTrace(); 341 } 342 } 343 } 344 345 return null; 346 } 347 @Override 348 public List<Picture> getVisitedPictures() { 349 // TODO Auto-generated method stub 350 ArrayList<Picture> result = new ArrayList<Picture>(); 351 Connection conn = null; 352 PreparedStatement ps = null; 353 try { 354 String sql = "select * from picture where isvisited = '1'"; 355 conn = ConnectDB.getConn();// 获得连接 356 ps = (PreparedStatement) conn.prepareStatement(sql); 357 ResultSet rs = ps.executeQuery(); 358 while (rs.next()) { 359 boolean visited; 360 name = rs.getString(1); 361 describe = rs.getString(2); 362 isVisit = rs.getInt(3); 363 album = rs.getInt(4); 364 images = rs.getString(5); 365 user = rs.getString(6); 366 367 if (isVisit == 1) { 368 visited = true; 369 } else { 370 visited = false; 371 } 372 Picture picture = new Picture(name, describe, visited, album, 373 images, user); 374 result.add(picture); 375 } 376 } catch (Exception e) { 377 // TODO: handle exception 378 e.printStackTrace(); 379 } finally { 380 ConnectDB.closeConn(conn); 381 if (ps != null) { 382 try { 383 ps.close(); 384 } catch (Exception e2) { 385 // TODO: handle exception 386 e2.printStackTrace(); 387 } 388 } 389 } 390 391 return result; 392 } 393 394 395 }
implement文件需要注意在import包时候,要加sql.....开头的,不要加mysql的
<V>
5,这里写了一个简单的jsp(其实是小组另一位同学写的啦)
好像是在菜鸟扒的吧。。哈哈哈,我也不懂
1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <%@ page language="java" contentType="text/html; charset=UTF-8" 4 pageEncoding="UTF-8"%> 5 <!DOCTYPE html > 6 <html> 7 <head> 8 9 <meta charset="utf-8"> 10 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 11 <meta name="viewport" content="width=device-width, initial-scale=1"> 12 <title>AddPic</title> 13 14 <link 15 href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" 16 rel="stylesheet"> 17 <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> 18 <script 19 src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> 20 21 </head> 22 <body> 23 24 25 <div class="container-fluid"> 26 27 <div class="col-md-12 column"> 28 <form:form class="form-horizontal" commandName="picture" 29 action="${pageContext.request.contextPath}/save_Picture" 30 method="post" enctype="multipart/form-data"> 31 <form class="form-horizontal"> 32 33 34 <div class="form-group"> 35 <label for="PictureName">PictureName</label> 36 <form:input class="form-control" id="name" path="name" /> 37 </div> 38 <div class="form-group"> 39 <label for="Picturedescribe">PicturDescribe</label> 40 <form:input class="form-control" id="describe" path="describe" /> 41 </div> 42 43 <div class="form-group"> 44 <label for="user">user</label> 45 <form:input class="form-control" id="user" path="user" /> 46 </div> 47 48 <div class="form-group"> 49 <label for="album">album</label> 50 <form:input class="form-control" id="album" path="album" /> 51 </div> 52 53 <div class="form-group"> 54 <label for="exampleInputFile">File input</label> <input 55 class="form-control" name="picture" type="file" /> <input 56 class="form-control" name="image" type="hidden" value="default" /> 57 </div> 58 59 60 61 <div> 62 <input type="radio" name="isvisited" value="1">isVisited <input 63 type="radio" name="isvisited" value="0">unVisited 64 </div> 65 <button type="submit" class="btn btn-default">Submit</button> 66 </form> 67 </form:form> 68 </div> 69 70 </div> 71 72 73 <script src="https://code.jquery.com/jquery.js"></script> 74 <script 75 src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script> 76 </body> 77 </html>
其实这个就是利用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的相关代码可以实现展示~~~~
就这样吧