基于spring2.0实现blog相册管理(文件上传+目录管理)

 

blog实现相册管理
目的:
 基于spring2.0实现blog相册管理,主要包括:
 目录管理:新建目录,修改目录,删除目录,查看目录
 图片管理:图片文件,修改图片,删除图片,查看图片,移动图片
<!--========================package=================================-->
步骤:
一:包结构
-blog
|    |+config
|    |  |-blog-servlet.xml
|    |+lib
|    |+src
|    | |-src
|    | |    |-com
|    | |    | |-wiscom
|    | |    | | |-file
|    | |    | | |    |+model
|    | |    | | |    |-web
|    | |    | | |    |  |-admin
|    |-web
|    | |+image
|    | |+upload
|    | |+WEB-INF
|    |  |-build.xml
<!--======================spring fileupload==========================-->
二:文件上传
1: 说明:spring提供对分段文件上传(multipart file upload)的支持,Spring支持web应用中的分段文件上传。这种支持是由即插即用的MultipartResolver来实现。这些解析器都定 义在org.springframework.web.multipart包里。Spring提供了现成的MultipartResolver可以支持 Commons FileUpload( http://jakarta.apache.org/commons/fileupload)和 COS FileUpload( http://www.servlets.com/cos)。本章后面的部分描述了Spring是如何支持文件上传的。
通 常情况下,Spring是不处理文件上传的,因为一些开发者想要自己处理它们。如果想使用Spring的这个功能,需要在web应用的上下文中添加分段文 件解析器。这样,每个请求就会被检查是否包含文件上传。如果没有,这个请求就被正常的处理,否则,应用上下文中已经定义的 MultipartResolver就会被调用。然后,你请求中的文件属性就会像其它属性一样被处理。
<!--=======================multipartResolver==========================-->
2:本例子实现commons fileupload.先在工程lib中加入jar包commons-fileupload.jar。
 在config中的blog-servlet.xml加入MultipartResolver
<bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- set the max upload size 500KB -->
 <property name="maxUploadSize">
     <value>51200</value>
 </property>
 <property name="maxInMemorySize">
     <value>4096</value>
 </property>
</bean>
<!--==========================以下为model================================-->
<!--==========================以下为model================================-->
<!--==========================以下为model================================-->
<!--=========================FileUpload.java=============================-->
3:在blog\src\com\wiscom\file\model中实现FileUpload的model
package com.wiscom.file.model;
public class FileUpload {
    private String parentDirectoryId;//文件存放在哪个虚拟目录下
    private byte[] file;//文件字节流
   
    private String description;//文件的描述
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
 public byte[] getFile() {
  return file;
 }
 public void setFile(byte[] file) {
  this.file = file;
 }
 public String getParentDirectoryId() {
  return parentDirectoryId;
 }
 public void setParentDirectoryId(String parentDirectoryId) {
  this.parentDirectoryId = parentDirectoryId;
 }
}
<!--========================UploadFile.java============================-->
4:在blog\src\com\wiscom\file\model中实现UploadFile的model
package com.wiscom.file.model;
/**
*UploadFile是数据库中关于被上传文件的信息的一个table
*例如上传的图片文件名为:picture.jpg
*
*/
import java.util.Date;
public class UploadFile {
 private String id=null;//文件的id
 private String fileOriginalName=null;//原始名称,picture
 private String alias = null;//别名
 private String parentDirectoryId = null;//位于哪个虚拟目录下
 private String type = null;//文件的归属类型,相册album
 private Date uploadTime = null;//上传时间
 private Date updateTime = null;//更新时间
 private String userId = null;//用户ID
 private String postfix  = null;//文件后缀jpg
 private String fileSize = null;//文件大小
 private String description = null;//文件描述
 
 public String getFileSize() {
  return fileSize;
 }
 public void setFileSize(String fileSize) {
  this.fileSize = fileSize;
 }
 public String getAlias() {
  return alias;
 }
 public void setAlias(String alias) {
  this.alias = alias;
 }
 public String getParentDirectoryId() {
  return parentDirectoryId;
 }
 public void setParentDirectoryId(String parentDirectoryId) {
  this.parentDirectoryId = parentDirectoryId;
 }
 public String getFileOriginalName() {
  return fileOriginalName;
 }
 public void setFileOriginalName(String fileOriginalName) {
  this.fileOriginalName = fileOriginalName;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getPostfix() {
  return postfix;
 }
 public void setPostfix(String postfix) {
  this.postfix = postfix;
 }
 public String getType() {
  return type;
 }
 public void setType(String type) {
  this.type = type;
 }
 public Date getUpdateTime() {
  return updateTime;
 }
 public void setUpdateTime(Date updateTime) {
  this.updateTime = updateTime;
 }
 public Date getUploadTime() {
  return uploadTime;
 }
 public void setUploadTime(Date uploadTime) {
  this.uploadTime = uploadTime;
 }
 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
<!--=============================Directory.java===============================-->
5:在blog\src\com\wiscom\file\model中实现虚拟目录Directory
package com.wiscom.file.model;
import java.util.Date;
/**
*Directory是数据库中关于用户自己创建目录的一个table
*例如上传的图片文件名为:"根目录\同学\大学同学\"
*
*/
public class Directory {
 String id = null;//目录ID
 String name = null;//目录名称,大学同学
 String directory = null;//目录全名,"根目录\同学\大学同学\"
 String parentDirectoryId = null;//上一层目录的ID,目录"根目录\同学\"的ID
 int priority = 10;//排序号,实现同级目录的排序
 String type= null;//目录的归属类型,相册album
 String userId = null;//用户ID
 boolean allow = true;//该目录是否可见
 Date createTime;//创建时间
 Date updateTime;//修改时间
 String description = null;//目录描述
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
 public Date getCreateTime() {
  return createTime;
 }
 public void setCreateTime(Date createTime) {
  this.createTime = createTime;
 }
 public Date getUpdateTime() {
  return updateTime;
 }
 public void setUpdateTime(Date updateTime) {
  this.updateTime = updateTime;
 }
 public boolean getAllow() {
  return allow;
 }
 public void setAllow(boolean allow) {
  this.allow = allow;
 }
 public String getDirectory() {
  return directory;
 }
 public void setDirectory(String directory) {
  this.directory = directory;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getPriority() {
  return priority;
 }
 public void setPriority(int priority) {
  this.priority = priority;
 }
 public String getType() {
  return type;
 }
 public void setType(String type) {
  this.type = type;
 }
 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public String getParentDirectoryId() {
  return parentDirectoryId;
 }
 public void setParentDirectoryId(String parentDirectoryId) {
  this.parentDirectoryId = parentDirectoryId;
 }
}
<!--===========================以下为DAO===================================-->
<!--===========================以下为DAO===================================-->
<!--===========================以下为DAO===================================-->
<!--============================UPLOADFILE表===============================-->
<!--=======================UploadFileManager.java==========================-->
6:blog\src\com\wiscom\file\service下的UploadFileManager接口,体现面向接口编程:
package com.wiscom.file.service;
/**
 * @author [email protected]
 *
 */
import com.wiscom.file.model.UploadFile;
import java.util.List;
public interface UploadFileManager {
 //根据ID从表中获得一个上传文件
 public UploadFile getFile(String id) throws UploadFileNotFoundException;
 //在表中保存一个上传文件的记录
 public void saveFile(UploadFile uploadFile);
 //在表中删除一个上传文件的记录
 public void removeFile(String fileId);
 //在表中根据真实文件名获得一个上传文件的记录
 public UploadFile getFilesByFileOriginalName(String fileOriginalName);
 //在表中根据别名获得一个上传文件的记录
 public UploadFile getFileByAlias(String alias);
 //列出该目录下的所有文件
 public List getFilesByParentDirectoryId(String parentDirectoryId);
 //根据归属查(这里就是album)找整站所有文件
 public List getFilesByType(String type);
 //根据归属查(这里就是album)找该用户所有文件
 public List getFilesByType(String userId,String type);
 //根据用户ID查出所有文件
 public List getFilesByUserId(String userId);
 //根据文件后缀查出所有文件
 public List getFilesByPostfix(String postfix);
 //将srcId目录下的文件文件转移到destId目录下
 public void moveFileDirectory(String srcId,String destId);
 //检查用户userId是否存有type归属(这里是album)的fileOriginalName.postfix的文件
 public boolean checkFileExist(String fileOriginalName,String postfix,String type,String userId);
}
<!--=====================AbstractUploadFileManager.java===================-->
7:抽象类AbstractUploadFileManager,主要是是保存和删除记录,不涉及基本sql
在blog\src\com\wiscom\file\service\impl下
package com.wiscom.file.service.impl;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.UploadFileManager;
public abstract class AbstractUploadFileManager extends JdbcDaoSupport implements UploadFileManager {
 private static Log logger = LogFactory.getFactory().getInstance(
   AbstractUploadFileManager.class);
 protected DataFieldMaxValueIncrementer idGenerator;
 public void setIdGenerator(DataFieldMaxValueIncrementer idGenerator) {
  this.idGenerator = idGenerator;
 }
 public void saveFile(UploadFile uploadFile) {
  if (uploadFile.getId() == null) {
   uploadFile.setId(idGenerator.nextStringValue());
   insertFile(uploadFile);
  } else {
   updateFile(uploadFile);
  }
 }
 public void removeFile(String fileId) {
  try {
   UploadFile uploadFile = getFile(fileId);
   deleteFile(fileId);
  } catch (Exception e) {
   logger.error(e);
  }
 }
 public void moveFileDirectory(String srcId,String destId){
  List files = getFilesByParentDirectoryId(srcId);
  updateFileDirectory(srcId, destId);
   for (int i = 0; i < files.size(); i++) {
    UploadFile uploadFile = (UploadFile) files.get(i);
    uploadFile.setParentDirectoryId(destId);
         }
 }
 
 abstract void updateFileDirectory(String srcId,String destId);
 abstract void insertFile(UploadFile uploadFile);
 abstract void updateFile(UploadFile uploadFile);
 
 abstract void deleteFile(String fileId);
}
<!--=====================GeneralUploadFileManager.java========================-->
8:基本DAO的实现类GeneralUploadFileManager
package com.wiscom.file.service.impl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.UploadFileNotFoundException;
public class GeneralUploadFileManager extends AbstractUploadFileManager {
 public void deleteFile(String fileId) {
  String sql = "delete from UPLOADFILE where ID=?";
  getJdbcTemplate().update(sql, new Object[] { fileId });
 }
 
 public boolean checkFileExist(String fileOriginalName,String postfix,String type,String userId) {
  String sql="select count(*) from UPLOADFILE where FILEORIGINALNAME=? And POSTFIX=? And TYPE=? And USERID=?";
  return getJdbcTemplate().queryForInt(sql,new Object[] { fileOriginalName,postfix,type,userId })>0;
 }
 public void insertFile(final UploadFile uploadFile) {
  String sql = "insert into UPLOADFILE (ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION) "
    + " values (?,?,?,?,?,?,?,?,?,?,?)";
  getJdbcTemplate().update(sql, new PreparedStatementSetter() {
   public void setValues(PreparedStatement ps) throws SQLException {
    ps.setString(1, uploadFile.getId());
    ps.setString(2, uploadFile.getFileOriginalName());
    ps.setString(3, uploadFile.getAlias());
    ps.setString(4, uploadFile.getParentDirectoryId());
    ps.setString(5, uploadFile.getType());
    ps.setTimestamp(6, new java.sql.Timestamp((uploadFile.getUploadTime().getTime())));
    ps.setTimestamp(7, new java.sql.Timestamp((uploadFile.getUpdateTime().getTime())));
    ps.setString(8, uploadFile.getUserId());
    ps.setString(9, uploadFile.getPostfix());
    ps.setString(10, uploadFile.getFileSize());
    ps.setString(11, uploadFile.getDescription());
   }
  });
 }

 public void updateFile(final UploadFile uploadFile) {
  String sql = "update UPLOADFILE set FILEORIGINALNAME=?,PARENTDIRECTORYID=?,TYPE=?,UPDATETIME=?,DESCRIPTION=? where ID=?";
  getJdbcTemplate().update(sql, new PreparedStatementSetter() {
   public void setValues(PreparedStatement ps) throws SQLException {
    ps.setString(1, uploadFile.getFileOriginalName());
    ps.setString(2, uploadFile.getParentDirectoryId());
    ps.setString(3, uploadFile.getType());
    ps.setTimestamp(4, new java.sql.Timestamp((uploadFile.getUpdateTime().getTime())));
    ps.setString(5, uploadFile.getDescription());
    ps.setString(6, uploadFile.getId());
   }
  });
 }
 public UploadFile getFile(String id) throws UploadFileNotFoundException {
  try{
   return (UploadFile) getJdbcTemplate().queryForObject(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where ID=?",
     new Object[] { id }, new FileMapper());   
  } catch(EmptyResultDataAccessException erde){
   throw new UploadFileNotFoundException();
  }
 }
 public UploadFile getFileByAlias(String alias) {
  try{
   return (UploadFile) getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where ALIAS=?",
     new Object[] { alias }, new FileMapper());   
  } catch(EmptyResultDataAccessException erde){
   throw new UploadFileNotFoundException();
  }
 }
 public List getFilesByParentDirectoryId(String parentDirectoryId) {
   return getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where PARENTDIRECTORYID=?",
     new Object[] { parentDirectoryId }, new FileMapper());   
 }
 public UploadFile getFilesByFileOriginalName(String fileOriginalName) {
  try{
   return (UploadFile) getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where FILEORIGINALNAME=?",
     new Object[] { fileOriginalName }, new FileMapper());   
  } catch(EmptyResultDataAccessException erde){
   throw new UploadFileNotFoundException();
  }
 }
 public List getFilesByPostfix(String postfix) {
   return getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where POSTFIX=?",
     new Object[] { postfix }, new FileMapper());   
 }
 
 public List getFilesByType(String type) {
   return getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where TYPE=?",
     new Object[] { type }, new FileMapper());   
 }
 public List getFilesByType(String userId,String type) {
   return getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where TYPE=? And USERID=?",
     new Object[] { type,userId }, new FileMapper());   
 }
 public List getFilesByUserId(String userId) {
   return getJdbcTemplate().query(
     "select ID,FILEORIGINALNAME,ALIAS,PARENTDIRECTORYID,TYPE,UPLOADTIME,UPDATETIME,USERID,POSTFIX,FILESIZE,DESCRIPTION from UPLOADFILE Where USERID=?",
     new Object[] { userId }, new FileMapper());  
 }
 
 
 private class FileMapper implements RowMapper {
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
   UploadFile uploadFile = new UploadFile();
   uploadFile.setId(rs.getString("ID"));
   uploadFile.setFileOriginalName(rs.getString("FILEORIGINALNAME"));
   uploadFile.setAlias(rs.getString("ALIAS"));
   uploadFile.setParentDirectoryId(rs.getString("PARENTDIRECTORYID"));
   uploadFile.setType(rs.getString("TYPE"));
   uploadFile.setUploadTime(rs.getTime("UPLOADTIME"));
   uploadFile.setUpdateTime(rs.getTime("UPDATETIME"));
   uploadFile.setUserId(rs.getString("USERID"));
   uploadFile.setPostfix(rs.getString("POSTFIX"));
   uploadFile.setFileSize(rs.getString("FILESIZE"));
   uploadFile.setDescription(rs.getString("DESCRIPTION"));
   return uploadFile;
  }
 }

 public void updateFileDirectory(String srcId, String destId) {
  String sql = "update UPLOADFILE set PARENTDIRECTORYID=? WHERE PARENTDIRECTORYID = ?";
        getJdbcTemplate().update(sql, new Object[]{destId, srcId});
 }
}
<!--=======================================================================-->
<!--=======================================================================-->
<!--=======================================================================-->
<!--============================DIRECTORY表================================-->
<!--============================DirectoryManager.java======================-->
9:blog\src\com\wiscom\file\service下的DirectoryManager接口,体现面向接口编程
package com.wiscom.file.service;
import java.util.List;
import com.wiscom.file.model.Directory;
public interface DirectoryManager {
 //根据Directory的ID获得Directory
 public Directory getDirectory(String id) throws DirectoryNotFoundException;
 //保存Directory
 public void saveDirectory(Directory directory);
 //删除Directory
 public void removeDirectory(String directoryId);
 //获得当前用户type(这里自由album)归属的所有Directory
 public List getDirectoriesByType(String type,String userId);
 //获得当前用户type(这里自由album)归属的所有Directory,排列与上面有别
 public List getDirectoriesListByType(String type,String userId);
 //获得parentDirectoryId目录下的所有目录
 public List getDirectoriesByParentDirectoryId(String parentDirectoryId);
 //获得用户userId,归属为type,directoryId目录下的所有目录
 public List getDirectoriesByDirectory(String directoryId,String userId,String type);
 //获得归属为type的根目录,如album的根目录为"根目录\"
 public Directory getRootDirectory(String userId,String type);
 //把srcId下的所有目录转移到destId目录下
 public void moveParentDirectory(String srcId,String destId);
 //查看userId的directoryId目录下是否有目录或文件
 public boolean checkDirectoryUsed(String directoryId,String userId);
}
<!--===================AbstractDirectoryManager.java========================-->
10:抽象类AbstractDirectoryManager,主要是是保存和删除记录,不涉及基本sql
在blog\src\com\wiscom\file\service\impl下
package com.wiscom.file.service.impl;
import java.util.List;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
import com.wiscom.file.model.Directory;
import com.wiscom.file.service.DirectoryManager;
public abstract class AbstractDirectoryManager extends JdbcDaoSupport implements DirectoryManager{
 
  protected DataFieldMaxValueIncrementer idGenerator;
 public void setIdGenerator(DataFieldMaxValueIncrementer idGenerator) {
  this.idGenerator = idGenerator;
 }
 public void saveDirectory(Directory directory) {
  if (directory.getId() == null||directory.getId().equals("")) {
   directory.setId(idGenerator.nextStringValue());
   insertDirectory(directory);
  } else {
   updateDirectory(directory);
  }
 }
 public void removeDirectory(String directoryId) {
  try {
   Directory directory = getDirectory(directoryId);
   deleteDirectory(directoryId);
  } catch (Exception e) {
   logger.error(e);
  }
 }
 
 public void moveParentDirectory(String srcId,String destId){
  List directories = getDirectoriesByParentDirectoryId(srcId);
  updateParentDirectory(srcId, destId);
   for (int i = 0; i < directories.size(); i++) {
    Directory File = (Directory) directories.get(i);
    File.setParentDirectoryId(destId);
 /*            indexService.rebuildEntry(Entry);*/
         }
 }
 
 abstract void updateParentDirectory(String srcId,String destId);
 
 abstract void insertDirectory(Directory directory);
 abstract void updateDirectory(Directory directory);
 
 abstract void deleteDirectory(String directoryId);
 
}
<!--==================GeneralDirectoryManager.java====================-->
11:基本DAO的实现类GeneralDirectoryManager
package com.wiscom.file.service.impl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import com.wiscom.file.model.Directory;
import com.wiscom.file.service.DirectoryNotFoundException;

public class GeneralDirectoryManager extends AbstractDirectoryManager {
 public void deleteDirectory(String directoryId) {
  String sql = "delete from DIRECTORY where ID=?";
  getJdbcTemplate().update(sql, new Object[] { directoryId });
 }
 public void insertDirectory(final Directory directory) {
  String sql = "insert into DIRECTORY (ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION) "+ " values (?,?,?,?,?,?,?,?,?,?,?)";
  getJdbcTemplate().update(sql, new PreparedStatementSetter() {
   public void setValues(PreparedStatement ps) throws SQLException {
    ps.setString(1, directory.getId());
    ps.setString(2, directory.getName());
    ps.setString(3, directory.getDirectory());
    ps.setString(4, directory.getParentDirectoryId());
    ps.setInt(5, directory.getPriority());
    ps.setString(6, directory.getType());
    ps.setString(7, directory.getUserId());
    ps.setInt(8, directory.getAllow()?1:0);
    ps.setTimestamp(9, new java.sql.Timestamp((directory.getCreateTime().getTime())));
    ps.setTimestamp(10, new java.sql.Timestamp((directory.getUpdateTime().getTime())));
    ps.setString(11, directory.getDescription());
   }
  });
 }
 public void updateDirectory(final Directory directory) {
  String sql = "update DIRECTORY set NAME=?,DIRECTORY=?,PARENTDIRECTORYID=?,PRIORITY=?,ALLOW=?,UPDATETIME=?,DESCRIPTION=? where ID=?";
  getJdbcTemplate().update(sql, new PreparedStatementSetter() {
   public void setValues(PreparedStatement ps) throws SQLException {
    ps.setString(1, directory.getName());
    ps.setString(2, directory.getDirectory());
    ps.setString(3, directory.getParentDirectoryId());
    ps.setInt(4, directory.getPriority());
    ps.setInt(5, directory.getAllow()?1:0);
    ps.setTimestamp(6, new java.sql.Timestamp((directory.getUpdateTime().getTime())));
    ps.setString(7, directory.getDescription());
    ps.setString(8, directory.getId());
   }
  });
 }
 public List getDirectoriesByParentDirectoryId(String parentDirectoryId) {
   return getJdbcTemplate().query(
     "select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY Where PARENTDIRECTORYID=? Order By PRIORITY",
     new Object[] { parentDirectoryId}, new DirectoryMapper());   
 }
 public List getDirectoriesByType(String type, String userId) {
   return getJdbcTemplate().query(
     "select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY Where TYPE=? AND USERID=? Order By PRIORITY",
     new Object[] { type,userId }, new DirectoryMapper()); 
 }
 
 public List getDirectoriesListByType(String type, String userId) {
  return getJdbcTemplate().query(
    "select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY Where TYPE=? AND USERID=? Order By DIRECTORY",
    new Object[] { type,userId }, new DirectoryMapper()); 
}
 public Directory getDirectory(String id){
  try{
   return (Directory) getJdbcTemplate().queryForObject(
     "select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY Where ID=?",
     new Object[] { id }, new DirectoryMapper());   
  } catch(EmptyResultDataAccessException erde){
   throw new DirectoryNotFoundException();
  }
 }
 public Directory getRootDirectory(String userId,String type) {
  try{
   String sql="select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY WHERE NAME='根目录' AND USERID=? AND TYPE=?";
   return (Directory) getJdbcTemplate().queryForObject(sql, new Object[] { userId ,type }, new DirectoryMapper());   
  } catch(EmptyResultDataAccessException erde){
   throw new DirectoryNotFoundException();
  }  
 }

 
 private class DirectoryMapper implements RowMapper {
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
   Directory directory = new Directory();
   directory.setId(rs.getString("ID"));
   directory.setName(rs.getString("NAME"));
   directory.setDirectory(rs.getString("DIRECTORY"));
   directory.setParentDirectoryId(rs.getString("PARENTDIRECTORYID"));
   directory.setPriority(rs.getInt("PRIORITY"));
   directory.setType(rs.getString("TYPE"));
   directory.setUserId(rs.getString("USERID"));
   directory.setAllow((rs.getInt("ALLOW")==1));
   directory.setCreateTime(rs.getTime("CREATETIME"));
   directory.setUpdateTime(rs.getTime("UPDATETIME"));
   directory.setDescription(rs.getString("DESCRIPTION"));
   return directory;
  }
 }
 
 public boolean checkDirectoryUsed(String directoryId,String userId) {
  return getJdbcTemplate().queryForInt("select count(*) from file Where directoryid=? And USERID=?",new Object[]{directoryId,userId})>0;
 }
 public void updateParentDirectory(String srcId, String destId) {
  String sql = "update directory set PARENTDIRECTORYID=? WHERE PARENTDIRECTORYID = ?";
        getJdbcTemplate().update(sql, new Object[]{destId, srcId});
  
 }
 public List getDirectoriesByDirectory(String directory,String userId,String type) {
  return getJdbcTemplate().query(
    "select ID,NAME,DIRECTORY,PARENTDIRECTORYID,PRIORITY,TYPE,USERID,ALLOW,CREATETIME,UPDATETIME,DESCRIPTION from DIRECTORY Where USERID=? And TYPE=? And DIRECTORY LIKE ? Order By PRIORITY",
    new Object[] { userId,type,directory}, new DirectoryMapper()); 
 }
}
<!--=======================================================================-->
<!--=======================================================================-->
<!--=======================================================================-->
<!--=======================================================================-->
<!--=========================配置blog-servlet.xml==========================-->
12.在blog-servlet.xml中加入GeneralUploadFileManager与GeneralDirectoryManager的bean
sequnce:SEQ_WEBLOGFILE_ID和SEQ_WEBLOGDIRECTORY_ID能在插入记录是生成ID
GeneralUploadFileManager类继承AbstractUploadFileManager,AbstractUploadFileManager
把idGenerator作为自己的属性,AbstractUploadFileManager又继承JdbcDaoSupport,
JdbcDaoSupport把dataSource作为自己的属性.
<bean id="com.wiscom.file.service.WeblogFileManager" parent="txProxyTemplate">
        <property name="target">
            <bean class="com.wiscom.file.service.impl.GeneralUploadFileManager">
                <property name="dataSource" ref="dataSource"/>
                <property name="idGenerator">
                    <bean class="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer">
                        <property name="dataSource" ref="dataSource"/>
                        <property name="incrementerName" value="SEQ_WEBLOGFILE_ID"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <bean id="com.wiscom.file.service.WeblogDirectoryManager" parent="txProxyTemplate">
        <property name="target">
            <bean class="com.wiscom.file.service.impl.GeneralDirectoryManager">
                <property name="dataSource" ref="dataSource"/>
                <property name="idGenerator">
                    <bean class="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer">
                        <property name="dataSource" ref="dataSource"/>
                        <property name="incrementerName" value="SEQ_WEBLOGDIRECTORY_ID"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
<!--=======================================================================-->
<!--=======================================================================-->
<!--=======================================================================-->
<!--=======================================================================-->
<!--==========================albumUpload.jsp===============================-->
13:文件上传页面,albumUpload.jsp
说明:对文件上传来说:enctype="multipart/form-data"和<input type="file">是必须的.
 
<%@ page pageEncoding="GB2312"%>
<%@ include file="/WEB-INF/jsp/include.jsp"%>
<form:form name="form1" method="post" action="albumUpload.htm"
 commandName="fileUpload" enctype="multipart/form-data" onsubmit="return mychk()">
 <form:errors path="*" />
 <table>
  <tr>
   <td>
    <spring:bind path="fileUpload.file">
     <input id="put" name='< c:out value="${status.expression}"/>'
      type="file" size="15" />
    </spring:bind>
   </td>
  </tr>
  <tr>
   <td>
    文件说明:
    <form:input path="description" />
   </td>
  </tr>
  <tr>
   <td>
   <spring:bind path="fileUpload.parentDirectoryId">
    <input type="submit" value="上载图片" />
    <input type="button" value="返回" onClick="location.href='<c:out value="${pageContext.request.contextPath}"/>/albumView.htm?parentDirectoryId=< c:out value="${status.value}"/>'"/>
   </spring:bind>
   </td>
  </tr>
 </table>
</form:form>
<script language="javascript">  
  function   mychk(){
       var s=document.getElementById("put").value.length;
              if(s>0)
                    {  
                    s=document.getElementById("put").value;
                    s=s.substring(s.length-4,s.length);
                    s=s.toLowerCase();
                  if((s==".jpg")||(s==".gif")||(s==".png")){  
                       return   true;
                        }  
                  else {  
                      alert("图片只支持jpg,gif,png格式,请检验并更正!");
                      document.getElementById("put").select();
                      return false;
                      }
                  }
      return   true;
      }
  </script>
<!--=============================include.jsp===============================-->
14:其中include.jsp为:
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fmt" uri=" http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="spring" uri=" http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri=" http://www.springframework.org/tags/form" %>
<!--=======================albumUpload.htm in Mapping=======================-->
blog-servlet.xml中加入:
<bean id="HandlerMapping"
 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 <property name="mappings">
     <props>
  <prop key="/albumUpload.htm">AlbumUploadController</prop>
                <prop key="/albumView.htm">AlbumViewController</prop>
                <prop key="/albumEdit.htm">AlbumEditController</prop>
                <prop key="/albumMove.htm">AlbumMoveController</prop>
                <prop key="/albumDelete.htm">AlbumDeleteController</prop>
    <prop key="/directoryCreate.htm">DirectoryCreateController</prop>
                <prop key="/directoryEdit.htm">DirectoryEditController</prop>
                <prop key="/directoryDelete.htm">DirectoryDeleteController</prop>
     </props>
        </property>
</bean>
<!--====================配置AlbumUploadController==========================-->
15:blog-servlet.xml中加入:
<bean id="AlbumUploadController" class="com.wiscom.file.web.admin.FileUploadController">
     <property name="type" value="album"/>
        <property name="uploadFileManager">
            <ref bean="com.wiscom.file.service.WeblogFileManager"/>
        </property>
        <property name="directoryManager">
            <ref bean="com.wiscom.file.service.WeblogDirectoryManager"/>
        </property>
        <property name="uploadDir" value="D:\blog\build\blog\upload\"/>
        <property name="commandName" value="fileUpload"/>
        <property name="sessionForm" value="true"/>
        <property name="formView" value="WEB-INF/jsp/albumUpload.jsp"/>
</bean>
<!--================实现AlbumUploadController.java==========================-->
16:com.wiscom.file.web.admin下实现图片上传控制器AlbumUploadController
package com.wiscom.file.web.admin;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.wiscom.file.model.FileUpload;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.DirectoryManager;
import com.wiscom.file.service.UploadFileManager;
import com.wiscom.file.web.Helper;
public class FileUploadController extends SimpleFormController {
 protected final Log log = LogFactory.getLog(FileUploadController.class);
 private String type; //文件归属(album)
 private String uploadDir;//存储目录
 private UploadFileManager uploadFileManager;
 private DirectoryManager directoryManager;
 public void setType(String type) {
  this.type = type;
 }
 public void setUploadFileManager(UploadFileManager uploadFileManager) {
  this.uploadFileManager = uploadFileManager;
 }
 public void setUploadDir(String uploadDir) {
  this.uploadDir = uploadDir;
 }
 public void setDirectoryManager(DirectoryManager directoryManager) {
  this.directoryManager = directoryManager;
 }
 //第一次请求页面(亦非submit操作)时返回的commandClass实例
 protected Object formBackingObject(HttpServletRequest request)
   throws Exception {
  FileUpload fileUpload = new FileUpload();
  fileUpload.setParentDirectoryId(request.getParameter("parentDirectoryId"));
   return fileUpload;
 }
 //对Command的特定的Field做格式化操作
 protected void initBinder(HttpServletRequest request,
   ServletRequestDataBinder binder) throws ServletException {
  binder.registerCustomEditor(byte[].class,new ByteArrayMultipartFileEditor());
 }
 //上传提交操作的处理
 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command, BindException errors)
   throws ServletException, IOException {
  if (type!=null&&type.equals("album")) {
   //将command表单转成FileUpload的类型,有三个属性:
   //parentDirectoryId:
   //file:分段字节流
   //description:
   FileUpload bean = (FileUpload) command;
   //从bean获得字节流
   byte[] bytes = bean.getFile();
   //request转成MultipartHttpServletRequest类型
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   //在multipartRequest中将名称为file的属性取出
   //file只包含一些文件的基本信息,如名称,不包含文件本身的字节流,file格式如下(例子):
   //-fileItem
   //|  | catchdContent=null
   //|  |+contentType="image/pjpeg"
   //|  |+dfos=DeferredFileOutputStream
   //|  | dfosFile=null
   //|  |+fieldName="file"
   //|  |+fileName="C:\Winter.jpg"
   //|  | isFormField=false
   //|  |+repository=File
   //|  | size=-1
   //|  | sizeThreshold=4096
   //-size=105542
   CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
   if (bytes == null) {
    //没有上传图片为空
    return new ModelAndView("/albumView.htm?parentDirectoryId="+bean.getParentDirectoryId());
   } else {
    //每个用户被分配名称为自己的ID号的文件夹
    String userUploadDir = uploadDir+ Helper.getCurrentUserId(request);
    File dirPath = new File(userUploadDir);
    //如果该文件夹不存在,则创建它
    if (!dirPath.exists()) {
     dirPath.mkdirs();
    }
    //操作系统的目录分隔符,windows为"\"
    String sep = System.getProperty("file.separator");
    //记入log4j日志
    if (log.isDebugEnabled()) {
     log.debug("uploading to: " + userUploadDir + sep
       + file.getOriginalFilename());
    }
    // 存入对照表
    int pointIndex = file.getOriginalFilename().lastIndexOf(".");
    if (pointIndex == -1) {
     return new ModelAndView("/albumView.htm?parentDirectoryId="+bean.getParentDirectoryId());
    }
    UploadFile uploadFile = new UploadFile();
    uploadFile.setFileOriginalName(file.getOriginalFilename()
      .substring(0, pointIndex));
    uploadFile.setPostfix(file.getOriginalFilename().substring(
      pointIndex + 1));
    // 以上传时间为别名
    Calendar calCurrent = Calendar.getInstance();
    long intTime = calCurrent.getTimeInMillis();
    int intDay = calCurrent.get(Calendar.DATE);
    int intMonth = calCurrent.get(Calendar.MONTH);
    int intYear = calCurrent.get(Calendar.YEAR);
    String alias = Integer.toString(intYear)
      + Integer.toString(intMonth) + Integer.toString(intDay)
      + Long.toString(intTime)
      + Integer.toString(new Random().nextInt(6));
    uploadFile.setAlias(alias);
    uploadFile.setType(type);
    uploadFile.setParentDirectoryId(bean.getParentDirectoryId());
    uploadFile.setUploadTime(new Date(new Date().getTime()));
    uploadFile.setUpdateTime(new Date(new Date().getTime()));
    uploadFile.setUserId(Helper.getCurrentUserId(request));
    uploadFile.setFileSize(Integer.toString(bytes.length / 1024));
    uploadFile.setDescription(bean.getDescription());
    // 检查文件是否存在
    if (!uploadFileManager.checkFileExist(uploadFile.getFileOriginalName(), uploadFile.getPostfix(),
      uploadFile.getType(), Helper.getCurrentUserId(request))) {
     // 存入数据库
     uploadFileManager.saveFile(uploadFile);
     // 存盘
     File uploadedFile = new File(userUploadDir + sep
       + uploadFile.getAlias() + "."
       + uploadFile.getPostfix());
     FileCopyUtils.copy(bytes, uploadedFile);
     // 生成略缩图
     try {
      File destFile = new File(userUploadDir + sep
        + Helper.getCurrentUserId(request) + "_"
        + uploadFile.getAlias() + "."
        + uploadFile.getPostfix()); // 将要转换出的小图文件
      AffineTransform transform = new AffineTransform();
      BufferedImage bis = ImageIO.read(uploadedFile);
      int w = bis.getWidth(); // 宽
      int h = bis.getHeight(); // 高
      int nw = 120; // 新宽
      int nh = (nw * h) / w; // 新高
      if (nh > 120) { // 重定义
       nh = 120;
       nw = (nh * w) / h;
      }
      double sx = (double) nw / w; // 宽比例
      double sy = (double) nh / h; // 高比例
      transform.setToScale(sx, sy); // 设置缩放比例
      AffineTransformOp ato = new AffineTransformOp(
        transform, null);
      BufferedImage bid = new BufferedImage(nw, nh,
        BufferedImage.TYPE_3BYTE_BGR);// 图层样式
      ato.filter(bis, bid); // 将bis强制转换成bid
      ImageIO.write(bid, "jpeg", destFile);
     } catch (Exception e) {
      e.printStackTrace();
     }
    } else {
     // 文件存在警告
    }
    return new ModelAndView("/albumView.htm?parentDirectoryId="+bean.getParentDirectoryId());
   }
  }
  return null;
 }
}
<!--============================修改图片===================================-->
<!--=========================配置blog-servlet.xml==========================-->
16. <bean id="AlbumEditController"
          class="com.wiscom.file.web.admin.FileEditController">
        <property name="uploadFileManager">
            <ref bean="com.wiscom.file.service.WeblogFileManager"/>
        </property>
        <property name="commandName" value="file"/>
        <property name="sessionForm" value="true"/>
        <property name="formView" value="WEB-INF/jsp/albumEdit.jsp"/>
    </bean>
<!--==============================albumEdit.jsp=============================-->
17.<%@ page pageEncoding="GB2312"%>
<%@ include file="/WEB-INF/jsp/include.jsp"%>
 
<form:form commandName="file" method="post" action="albumEdit.htm" onsubmit="return check()">
 <form:errors path="*" />
 <table>
  <tr>
   <h1 colspan="2">
    修改文件
   </h1>
  </tr>
  <form:hidden path="id" />
  <tr>
   <th>
    名 称
   </th>
   <td>
    <form:input path="fileOriginalName" id="fileOriginalName"/>
   </td>
  </tr>
  <tr>
   <th>
    描 述
   </th>
   <td>
    <form:input path="description" />
   </td>
  </tr>
  <tr>
   <th colspan="2">
   <spring:bind path="file.parentDirectoryId">
    <input type="submit" value="保存" />
    <input type="button" value="返回" onClick="location.href='<c:out value="${pageContext.request.contextPath}"/>/albumView.htm?parentDirectoryId=< c:out value="${status.value}"/>'"/>
   </spring:bind>
   </th>
  </tr>
 </table>
</form:form>
<script>
function check(){
if(document.getElementById("fileOriginalName").value.length<1){
    alert("名称不能为空");
    return false;
  }
 return true;
}
</script>
<!--============================实现FileEditController.java================-->
18.=实现FileEditController
package com.wiscom.file.web.admin;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.UploadFileManager;
public class FileEditController extends SimpleFormController  {
 private UploadFileManager uploadFileManager;
 public void setUploadFileManager(UploadFileManager uploadFileManager) {
  this.uploadFileManager = uploadFileManager;
 }
 protected Object formBackingObject(HttpServletRequest request) throws Exception {
  return  uploadFileManager.getFile(request.getParameter("weblogFileId"));
 }
 protected void initBinder(HttpServletRequest request,
   ServletRequestDataBinder binder) throws Exception {
  binder.setAllowedFields(new String[] { "fileOriginalName", "parentDirectoryId","description" });
 }
 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command,
   BindException bindException) throws Exception {
  UploadFile uploadFile = (UploadFile) command;
  uploadFile.setUpdateTime(new Date(new Date().getTime()));
  uploadFileManager.saveFile(uploadFile);
  if(uploadFile.getType().equals("album")){
  return new ModelAndView("/albumView.htm?parentDirectoryId="+uploadFile.getParentDirectoryId());
  }
  if(uploadFile.getType().equals("attachment")){
   return new ModelAndView(getSuccessView());
   }
  return null;
 }
}
<!--============================删除图片===================================-->
<!--=========================配置blog-servlet.xml==========================-->
19.配置AlbumDeleteController
    <bean id="AlbumDeleteController" class="com.wiscom.file.web.admin.FileDeleteController">
        <property name="uploadDir" value="D:\blog\build\blog\upload\"/>
        <property name="uploadFileManager">
            <ref bean="com.wiscom.file.service.WeblogFileManager"/>
        </property>
        <property name="viewName" value="/albumView.htm"/>
    </bean>
<!--===================实现AlbumDeleteController.java===========================-->
20.实现AlbumDeleteController
package com.wiscom.file.web.admin;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.UploadFileManager;
import com.wiscom.file.web.Helper;
public class FileDeleteController  extends ParameterizableViewController{
 private String uploadDir; 
 private UploadFileManager uploadFileManager;
 
 public void setUploadDir(String uploadDir) {
  this.uploadDir = uploadDir;
 }
 public void setUploadFileManager(UploadFileManager uploadFileManager) {
  this.uploadFileManager = uploadFileManager;
 }
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
  String uploadFileId = request.getParameter("weblogFileId");
  UploadFile uploadFile = uploadFileManager.getFile(uploadFileId);
  uploadFileManager.removeFile(uploadFileId);
  String sep = System.getProperty("file.separator");
  String userUploadDir =uploadDir+Helper.getCurrentUserId(request);
  File uploadedFile = new File(userUploadDir+sep+uploadFile.getAlias()+"."+uploadFile.getPostfix());
  uploadedFile.delete();
  if(uploadFile.getType().equals("album")){
  File destFile = new File(userUploadDir + sep+Helper.getCurrentUserId(request)+"_"+uploadFile.getAlias()+"."+uploadFile.getPostfix());
  destFile.delete();
  return new ModelAndView("/albumView.htm?parentDirectoryId="+uploadFile.getParentDirectoryId());
  }
  return new ModelAndView(getViewName());
 }
}
<!--============================移动图片===================================-->
<!--=========================配置blog-servlet.xml==========================-->
21.配置AlbumMoveController
<bean id="AlbumMoveController" class="com.wiscom.file.web.admin.FileMoveController">
        <property name="uploadFileManager">
            <ref bean="com.wiscom.file.service.WeblogFileManager"/>
        </property>
        <property name="viewName" value="/albumView.htm"/>
</bean>
<!--=====================实现AlbumMoveController.java=========================-->
22.实现AlbumMoveController
package com.wiscom.file.web.admin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import com.wiscom.file.model.UploadFile;
import com.wiscom.file.service.UploadFileManager;
public class FileMoveController extends ParameterizableViewController{
 private UploadFileManager uploadFileManager;
 public void setUploadFileManager(UploadFileManager uploadFileManager) {
  this.uploadFileManager = uploadFileManager;
 }
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
  UploadFile uploadFile = uploadFileManager.getFile(request.getParameter("fileId"));
  String parentDirectoryId = uploadFile.getParentDirectoryId();
  uploadFile.setParentDirectoryId(request.getParameter("targetDirectoryId"));
  uploadFileManager.saveFile(uploadFile);
  if(uploadFile.getType().equals("album")){
   return new ModelAndView("/albumView.htm?parentDirectoryId="+parentDirectoryId);
  }
  return new ModelAndView(getViewName());
 }
}
<!--=========================目录操作======================================-->
<!--=========================新建目录======================================-->
<!--======================配置blog-servlet.xml============================-->
23.配置 DirectoryCreateController
<bean id="DirectoryCreateController" class="com.wiscom.file.web.admin.DirectoryCreateController">
     <property name="directoryManager">
   <ref bean="com.wiscom.file.service.WeblogDirectoryManager" />
  </property>
  <property name="commandName" value="directory" />
  <property name="sessionForm" value="true" />
  <property name="formView" value="WEB-INF/jsp/directoryCreate.jsp" />
  <property name="validator">
            <ref bean="DirectoryValidator"/>
        </property>
</bean>
<!--========================directoryCreate.jsp============================-->
24.directoryCreate.jsp
<%@ page pageEncoding="GB2312"%>
<%@ include file="/WEB-INF/jsp/include.jsp"%>
<form:form method="post" action="directoryCreate.htm" name="formcrate" commandName="directory" >
 <form:errors path="*" />
 <table>
  <tr>
   <h1 colspan="2">
    目录操作
   </h1>
  </tr>
  <form:hidden path="id" />
  <tr>
   <th>
    名 称
   </th>
   <td>
    <form:input path="name" id="name"/>
   </td>
  </tr>
  <tr>
   <th>
    显示顺序
   </th>
   <td>
    <form:input path="priority" id="priority"/>
   </td>
  </tr>
  <tr>
   <th>
    描 述
   </th>
   <td>
    <form:input path="description" />
   </td>
  </tr>
  <tr>
   <th colspan="2">
    <spring:bind path="directory.parentDirectoryId">
     <input type="button" value="保存" onClick="check()"/>
     <input type="button" value="返回" onClick="location.href='<c:out value="${pageContext.request.contextPath}"/>/albumView.htm?parentDirectoryId=<c:out value='${status.value}'/>'" />
    </spring:bind>
   </th>
  </tr>
 </table>
</form:form>
<script language="javascript">
function check(){
if(document.getElementById("name").value.length<1){
    alert("名称不能为空");
    return false;
  }if(checknumber(document.getElementById("priority").value)==false){
      alert("排序必须为数字");
    return false;
 }
 document.formcrate.submit();
 return true;
}
function checknumber(String)
{
   var Letters = "1234567890";
   var i;
   var c;
   for( i = 0; i < String.length; i ++ )
   {
       c = String.charAt( i );
       if (Letters.indexOf( c ) ==-1)
       {
           return false;
       }
   }
   return true;
}
</script>
<!--=================实现DirectoryCreateController.java====================-->
25.实现DirectoryCreateController
package com.wiscom.file.web.admin;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.wiscom.file.model.Directory;
import com.wiscom.file.service.DirectoryManager;
import com.wiscom.file.web.Helper;
public class DirectoryCreateController extends SimpleFormController {
 
 private DirectoryManager directoryManager;
 public void setDirectoryManager(DirectoryManager directoryManager) {
  this.directoryManager = directoryManager;
 }
 
 protected Object formBackingObject(HttpServletRequest request) throws Exception {
  Directory directory = new Directory();
  directory.setParentDirectoryId(directoryManager.getDirectory(request.getParameter("parentDirectoryId")).getId());
  directory.setType(directoryManager.getDirectory(request.getParameter("par

<!--EndFragment-->

你可能感兴趣的:(spring)