- 浏览: 110410 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (87)
- SQL语句优化技术分析 (3)
- SQL SERVER查询优化 (2)
- JDBC查询优化 (1)
- 服务器调优 (1)
- 100 Best Quotes On Leadership (1)
- Java NIO Chinese Tutorial (1)
- spring security (1)
- JAVA线程池的分析和使用 (1)
- Java并发 (1)
- Java NIO框架Mina (1)
- Netty (1)
- Grizzly比较 (1)
- What Factors Justify the Use of Apache Hadoop? (1)
- Instagram工程师教你如何改善App的性能 (1)
- The Ubuntu's Directory Tree (1)
- JVM调优总结 -Xms -Xmx -Xmn -Xss (1)
- Tomcat configuration recommendations (1)
- Java 7 并发编程指南 (1)
- Java完整并发教程 (1)
- Java公钥私钥签名工具包应用实例 (1)
- Java集群解决方案 (1)
- Memcache和Redis比较 (1)
- 大型网站系统架构的演化 (1)
- 天猫浏览型应用的CDN静态化架构演变 (1)
- 淘宝的架构 (1)
- 大规模网站架构的缓存机制和几何分形学 (1)
- 敏捷开发 (1)
- 什么时候用MongoDB? (1)
- Java算法 (1)
- OAuth 2.0概览 (1)
- 全面理解OAuth 2.0 (1)
- Java工程师面试必问题目 (1)
最新评论
-
zhanggeng22:
[b][i][u]引用[list]
[*][img][url] ...
tomcat 的server.xml配置详解,看完你100%熟练配置tomcat -
yangsong158:
好文章,必需顶一个
大规模网站架构的缓存机制和几何分形学 -
卖火柴的老特工:
request.getparameter是获取通过get或则p ...
Request的getParameter()和getAttribute()方法的区别 -
zhuzhiguosnail:
终于能恢复了
十三个价值连城的成功习惯 -
liuwenbo200285:
sturts1 action是单例模式,线程是安全的。 ...
Java常碰面试题
首先是表单(采用springMVC模式,标签模板)documentForm.jsp
<%@ page contentType="text/html;charset=utf-8"%>
<%@ include file="/commons/taglibs.jsp"%>
<template:insert template="/commons/templates/form.jsp">
<!-- 指定标题 -->
<template:put name="title">项目文档信息编辑</template:put>
<!-- 指定head标签之间的附加内容-->
<template:put name="head">
<script language="javascript" src="${ctx}/scripts/datetimeSelect.js"
type="text/javascript"></script>
<script language="javascript" type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
//当表单提交时执行验证
var validator = $("#inputForm").validate( {
//表单提交的处理
submitHandler : function() {
//ajax提交表单 指定form名称和成功后跳转的地址
AjaxForm.submit("#inputForm",
"${ctx}/project/document/list.view");
}
});
if ("${action}".indexOf("insert") >= 0) {
//插入时
$("#file").focus();
}
});
function doExamine(id,state){
AjaxRequest.submit("examine.save", {
"id" : id,state:state
}, "${ctx}/project/document/list.view");
}
</script>
</template:put>
<!-- 指定表单内容 -->
<template:put name="form">
<!-- form的名称固定为mainForm -->
<form name="inputForm" id="inputForm" action="${action}" method="post"
enctype="multipart/form-data"><c:if
test="${sessionScope.employee.priv==1 && document.dataState!=1}">
<table class="form" cellspacing="1">
<tr>
<td width="120">资料截止日期<span class="notice">*</span></td>
<td width="300" class="special"><input type="text"
class="required text" name="endDate" id="endDate"
value="<c:out value="${document.endDate}"/>"
onclick="setDay(this);" /></td>
<td width="120">资料类型<span class="notice">*</span></td>
<td width="300" class="special"><select name="docType"
id="docType" title="请选择一个组" validate="required:true"
style="width: 152px;">
<option value="">请选择组</option>
<c:forEach items="${docTypes}" var="dt">
<c:choose>
<c:when test="${document.docType==dt}">
<option value="${dt}" selected="selected">${dt}</option>
</c:when>
<c:otherwise>
<option value="${dt}">${dt}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
</tr>
<tr>
<td>资料文档</td>
<td colspan="3"><input type="file" class="required text"
name="fileUpload" id="fileUpload" /></td>
</tr>
<tr>
<td colspan="4" align="left" height="50px"><c:if
test="${document.dataState==0 || document.dataState==3}">
<input type="submit" class="submit" value=" 保存 " />
</c:if> <input type="button" class="button" value="返回列表 "
onclick="window.location='${ctx}/project/document/list.view'" /></td>
</tr>
</table>
</c:if> <c:if
test="${sessionScope.employee.priv==2 || sessionScope.employee.priv==0 || (sessionScope.employee.priv==1 && document.dataState==1)}">
<table class="main" cellspacing="1">
<tr>
<td class="desc">资料截止日期</td>
<td width="300" class="special"><fmt:formatDate
value="${document.endDate}" type="date" dateStyle="long" /></td>
<td class="desc">资料类型</td>
<td width="300" class="special">${document.docType}</td>
</tr>
<tr>
<td class="desc">资料文档</td>
<td colspan="3"><a href="${ctx}/${document.document}">下载文档</a></td>
</tr>
<tr>
<td colspan="4" align="left" height="50px"><c:if
test="${document.dataState==1 && sessionScope.employee.priv==2}">
<input type="hidden" name="state" value="" id="state" />
<input type="button" class="button" value="审批通过 "
onclick="doExamine(${document.id},2);" />
<input type="button" class="button" value="审批不通过 "
onclick="doExamine(${document.id},3);" />
</c:if> <input type="button" class="button" value="返回列表 "
onclick="window.location='${ctx}/project/document/list.view'" />
</td>
</tr>
</table>
</c:if> <input type="hidden" name="id" value="${document.id} " /></form>
</template:put>
</template:insert>
下面是DocumentAction(采用spring的注释):
package com.ztev.fipmis.project;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import com.ztev.fipmis.BaseAction;
import com.ztev.fipmis.BaseService;
import com.ztev.fipmis.ServiceException;
import com.ztev.fipmis.SessionManager;
import com.ztev.fipmis.baseinfo.AdcdBean;
import com.ztev.fipmis.baseinfo.AdcdService;
import com.ztev.fipmis.baseinfo.EmployeeBean;
import com.ztev.fipmis.file.FileSystemSaver;
import com.ztev.fipmis.irrigation.util.AdcdIrUtil;
import com.ztev.pagination.PageParameterSimple;
/**
* 项目文档信息操作控制器。
*
* @author 朱志国 (zhu.zhiguo@hotmail.com) *
*/
@Controller
@RequestMapping("/project/document/")
public class DocumentAction extends BaseAction {
@InitBinder
public void initBinder(WebDataBinder binder){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
binder.registerCustomEditor(Date.class,new CustomDateEditor(format, true));
}
/**
* 项目文档处理业务实例
*/
@Autowired
private DocumentService documentService;
@Autowired
private AdcdService adcdService;
/**
* 显示列表,默认页面
*
* @param model
* @param pp
* 分页参数。
* @param user
* 查询条件
* @return
*/
@RequestMapping("list.view")
public String showList(Model model, PageParameterSimple pp,
Document document,HttpSession session,AdcdBean queryBean) {
//请求为空
if( StringUtils.isBlank(queryBean.getAdcd()) ){
/** 取得用户上次查询的行政区划信息**/
AdcdBean adcdBean = SessionManager.getQueryAdcdBean(session);
/** 上次查询的行政区划信息为空,使用当前权限默认查询**/
if( adcdBean == null ){
//查找当前权限下所有Adcd
EmployeeBean user = SessionManager.getEmployee(session);
//找到当前权限默认查询
BeanUtils.copyProperties(user, queryBean);
}else{
BeanUtils.copyProperties(adcdBean, queryBean);
}
}else{
/** 保存用户查询的行政区划信息**/
SessionManager.setQueryAdcdBean(session, queryBean);
}
//默认选中行政条件
model.addAttribute("queryAdcd", queryBean);
//用户查询行政区划
List<AdcdBean> rightAdcdBeans = adcdService.findListBylike(queryBean.getAdcd());
// 分页信息,名字固定为pageinfo
model.addAttribute("pageinfo", this.documentService.findPage(pp,
document,AdcdIrUtil.getAdcdsCodeStr(rightAdcdBeans)));
model.addAttribute("documentQuery", document);
return "project/document/documentList";
}// end showList
/**
* 显示插入表单
*
* @param model
* @return
*/
@RequestMapping("insert.form")
public String showInsert(Model model) {
Document document = new Document();
document.setDataState(0);
model.addAttribute("docTypes", BaseService.findAllDocType());
model.addAttribute("document", document);
model.addAttribute("action", "insert.save");
model.addAttribute("groups", "");
return "project/document/documentForm";
}// end showInsert
/**
* 显示修改页面
*
* @param userId
* 用户唯一标识。
* @param model
* @return
*/
@RequestMapping("update.form")
public String showUpate(@RequestParam("id") Integer documentId,
HttpSession session, Model model) {
Document document = this.documentService.find(documentId);
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
if (user.getPriv() == 2) {
model.addAttribute("action", "examine.save");
} else if (user.getPriv() == 1) {
model.addAttribute("action", "update.save");
}
model.addAttribute("docTypes", BaseService.findAllDocType());
model.addAttribute("document", document);
model.addAttribute("action", "update.save");
model.addAttribute("groups", "");
return "project/document/documentForm";
}// end showUpate
/**
* 执行插入
*
* @param user
* @return
*/
@RequestMapping("insert.save")
public void saveInsert(Document document, HttpServletResponse response,
DefaultMultipartHttpServletRequest request,HttpSession session) throws Exception {
MultipartFile multipartFile = document.getFileUpload();
FileSystemSaver saver = new FileSystemSaver();
Document docut = saver.save(multipartFile,request);
document.setDocument(docut.getDocument());
document.setName(docut.getName());
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
document.setInputTime(new Date(System.currentTimeMillis()));
document.setAdcd(user.getAdcd());
document.setDataState(0);
document.setInputEmpNo(user.getEmpNo());
try {
this.documentService.insert(document);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveInsert
@RequestMapping("download.view")
public void showdDwnload(@RequestParam("id") Integer id,HttpServletResponse response,HttpServletRequest request) throws Exception {
Document document = documentService.find(id);
try {
//document.setDocument(request.getRequestURL().toString().replaceAll(request.getRequestURI(), "")+ request.getContextPath()+document.getDocument());
FileSystemSaver saver = new FileSystemSaver();
saver.download(response, document,request);
} catch (ServiceException se) {
}
}// end saveInsert
/**
* 执行更新。
*
* @param user
* @return
*/
@RequestMapping("update.save")
public void saveUpdate(Document document, HttpServletResponse response,
DefaultMultipartHttpServletRequest request) throws Exception {
MultipartFile multipartFile = document.getFileUpload();
FileSystemSaver saver = new FileSystemSaver();
if (multipartFile!=null) {
Document docut = saver.save(multipartFile,request);
document.setDocument(docut.getDocument());
}
this.documentService.update(document);
super.printJson(response, true);
}// end saveUpdate
/**
* 执行更新。
*
* @param userId
* 用户唯一标识。
* @return
*/
@RequestMapping("delete.save")
public void saveDelete(Integer id, HttpServletResponse response,HttpServletRequest request)
throws Exception {
try {
String url=documentService.find(id).getDocument();
this.documentService.delete(id);
FileSystemSaver saver = new FileSystemSaver();
saver.delete(url, request);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveDelete
/**
* 提交审批。
*
* @param userId
* 用户唯一标识。
* @return
*/
@RequestMapping("examine.save")
public void saveExamine(@RequestParam("id") Integer id,
@RequestParam("state") Integer state, HttpServletResponse response,
HttpServletRequest request,HttpSession session) throws Exception {
try {
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
Document document = documentService.find(id);
if (document.getDataState() == 0) {
document.setDataState(1);
} else {
document.setDataState(state);
document.setApproveTime(new Date(System.currentTimeMillis()));
document.setApproveEmpNo(user.getEmpNo());
}
this.documentService.examine(document);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveDelete
}
以下是DocumentService:
package com.ztev.fipmis;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 业务操作的基类。
*
* @朱志国 (zhu.zhiguo@hotmail.com) *
*/
public class BaseService {
/**资金类别(来源)的类型标识*/
public static final String TYPE_DOC_TYPE = "document-type";
/**建设属性*/
public static final String IRBUILD_BEAN= "irbuild-bean";
/** 投资部门分类*/
public static final String INVERT_DEPT= "invest-Dept";
/**
* 日志操作句柄
*/
protected Log logger = LogFactory.getLog(getClass());
public static String[] findAllDocType(){
return BaseDataHelper.getValues(TYPE_DOC_TYPE);
}
public static Map<String, String> findIrbuildDec(){
return BaseDataHelper.getKeyDescriptionMap(IRBUILD_BEAN);
}
public static Map<String, String> findIrbuildValue(){
return BaseDataHelper.getKeyValueMap(IRBUILD_BEAN);
}
public static String[] findInvestDepart(){
return BaseDataHelper.getValues(INVERT_DEPT);
}
public static Map<String, String> findInvDepDscription(){
return BaseDataHelper.getKeyDescriptionMap(INVERT_DEPT);
}
public static BaseDataEntry[] findAllInvertDept(){
return BaseDataHelper.getEntries(INVERT_DEPT);
}
public static Map<String, String> findInvertDeptValue(){
return BaseDataHelper.getKeyValueMap(INVERT_DEPT);
}
}
以下是 FileSystemSaver :
package com.ztev.fipmis.file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import com.ztev.fipmis.ConfigManager;
import com.ztev.fipmis.StringUtils;
import com.ztev.fipmis.project.Document;
/**
* 将文档保存在文件系统中
*
* @author 李飞飞
*/
public class FileSystemSaver {
/**
* 判断该类型文件是否允许上传
*
* @param file
* @return
*/
protected boolean accept(String fileName) {
String filesDenied = ConfigManager.getProperty(ConfigManager.KEY_FILES_DENIED);
if (filesDenied == null)
return true;
StringTokenizer st = new StringTokenizer(filesDenied, ",");
while (st.hasMoreElements()) {
if (fileName.equalsIgnoreCase(st.nextToken()))
return false;
}
return true;
}
/**
* 下载文件方法
* @param response
* @param path 文件地址
* @param name 文件名
* @throws IOException
*/
public void download(HttpServletResponse response,Document document,HttpServletRequest request) throws IOException{
String fileName = new String(document.getName().getBytes("GBK"),"ISO8859-1");
response.setContentType( document.getDocType() ); //或gif等
response.setHeader("Content-Disposition", "attachment;filename=" +fileName);
//获取欲下载的文件输入流
String uploadPath = this.getUploadPath(request);
String baseURI = this.getPhotoBaseURI();
String path=uploadPath+ StringUtils.replace(document.getDocument().substring(baseURI.length()), "/",File.separator);
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
FileCopyUtils.copy(bis, response.getOutputStream());
response.getOutputStream().flush();
response.getWriter().flush();
response.getWriter().close();
}
/**
* 保存文件方法
*
* @param imgFile
* @param fileName
* @param autoRotate
* @param context
* @return
* @throws IOException
*/
@SuppressWarnings("null")
public Document save(MultipartFile file, DefaultMultipartHttpServletRequest request)
throws IOException {
Document document = new Document();
System.out.println("-----------得到文件名称--------"+file.getOriginalFilename()+"---------4--------");
//file.getOriginalFilename()得到文件名称(加后缀)而 getFileExtend得到文件的后缀名
String extendName = getFileExtend(file.getOriginalFilename());
System.out.println("-----------得到文件--------"+extendName+"---------6--------");
String[] urls = this.createNewPhotoURI(extendName, request);
if (urls == null && urls.length == 0)
return null;
String origionalPath = urls[0];
System.out.println("-----------7--------"+origionalPath+"---------7--------");
// 保存上传的文件
{
writeToFile(file, origionalPath);
}
// 计算图片的url
String uploadPath = this.getUploadPath(request);
System.out.println("------------5-----------"+uploadPath+"------------5--------");
//得到图片在文件夹的完整名称
String path = origionalPath.substring(uploadPath.length());
System.out.println("------------6-----------"+path+"------------6--------");
document.setDocument(getPhotoBaseURI()+ StringUtils.replace(path, File.separator, "/"));
System.out.println("------------8-----------"+getPhotoBaseURI()+"------------8--------");
document.setDocType(extendName);
document.setName(file.getOriginalFilename());
System.out.println("------------9-----------"+file.getOriginalFilename()+"------------9--------");
System.out.println(document.getDocument());
return document;
}
/**
* 判断是否为合法的文档
*
* @param extendName
* @return
*/
public static boolean isImage(String extendName) {
return "doc".equalsIgnoreCase(extendName)
|| "rar".equalsIgnoreCase(extendName)
|| "xls".equalsIgnoreCase(extendName)
|| "ppt".equalsIgnoreCase(extendName)
|| "txt".equalsIgnoreCase(extendName)
|| "pdf".equalsIgnoreCase(extendName);
}
/**
* 获取文件类型
* @param fn
* @return
*/
public String getFileExtend(String fn){
if(StringUtils.isEmpty(fn))
return null;
int idx = fn.lastIndexOf('.')+1;
if(idx==0 || idx >= fn.length())
return null;
return fn.substring(idx);
}
/**
* 将上传的保存到磁盘中
* 文件
* @param imgFile
* @param origionalPath
* @throws IOException
*/
public static void writeToFile(MultipartFile multifile, String origionalPath)
throws IOException {
File file=new File(origionalPath);
// 保存上传的文件
FileUtils.writeByteArrayToFile(file,multifile.getBytes());
}
/*
* (non-Javadoc)
*
* @see com.liusoft.dlog4j.photo.PhotoSaver#delete(java.lang.String)
*/
public boolean delete(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return f.delete();
return false;
}
/**
* 检测与创建一级、二级文件夹、文件名 这里我通过传入的两个字符串来做一级文件夹和二级文件夹名称
* 通过此种办法我们可以做到根据用户的选择保存到相应的文件夹下
*/
public File creatFolder(String typeName, String brandName, String fileName) {
File file = null;
typeName = typeName.replaceAll("/", ""); // 去掉"/"
typeName = typeName.replaceAll(" ", ""); // 替换半角空格
typeName = typeName.replaceAll(" ", ""); // 替换全角空格
brandName = brandName.replaceAll("/", ""); // 去掉"/"
brandName = brandName.replaceAll(" ", ""); // 替换半角空格
brandName = brandName.replaceAll(" ", ""); // 替换全角空格
File firstFolder = new File("c:/" + typeName); // 一级文件夹
if (firstFolder.exists()) { // 如果一级文件夹存在,则检测二级文件夹
File secondFolder = new File(firstFolder, brandName);
if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
file = new File(secondFolder, fileName);
} else { // 如果二级文件夹不存在,则创建二级文件夹
secondFolder.mkdir();
file = new File(secondFolder, fileName); // 创建完二级文件夹后,再合建文件
}
} else { // 如果一级不存在,则创建一级文件夹
firstFolder.mkdir();
File secondFolder = new File(firstFolder, brandName);
if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
file = new File(secondFolder, fileName);
} else { // 如果二级文件夹不存在,则创建二级文件夹
secondFolder.mkdir();
file = new File(secondFolder, fileName);
}
}
return file;
}
public InputStream read(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return new FileInputStream(f);
return null;
}
public OutputStream write(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return new FileOutputStream(f, false);
return null;
}
/**
* 生成一个用于存储文件并返回其URI地址
*
* @param ctx
* @param ext
* 例如: .gif
* @return
* @throws IOException
*/
private String[] createNewPhotoURI(String ext, HttpServletRequest context)
throws IOException {
Calendar cal = Calendar.getInstance();
StringBuffer dir = new StringBuffer();
dir.append(getUploadPath(context));
System.out.println("------------10-----------"+getUploadPath(context)+"------------10--------");
dir.append(cal.get(Calendar.YEAR));
System.out.println("------------11-----------"+dir.toString()+"------------11--------");
dir.append(File.separator);
System.out.println("------------12-----------"+dir.toString()+"------------12--------");
dir.append(cal.get(Calendar.MONTH) + 1);
dir.append(File.separator);
dir.append(cal.get(Calendar.DATE));
dir.append(File.separator);
System.out.println("------------13-----------"+dir.toString()+"------------13--------");
File file = new File(dir.toString());
if (!file.exists()) {
// 如果目录不存在则创建目录
synchronized (FileSystemSaver.class) {
if (!file.mkdirs())
return null;
}
}
file = null;
int times = 0;
do {
// 生成独一无二的文件名
String fn = String.valueOf(System.currentTimeMillis()) + '.' + ext;
System.out.println("------------14-----------"+fn+"------------14--------");
StringBuffer fn_preview = new StringBuffer();
fn_preview.append(System.currentTimeMillis());
fn_preview.append("_s.");
fn_preview.append(ext);
File f = new File(dir + fn);
File f_preview = new File(dir + fn_preview.toString());
System.out.println("------------15-----------"+dir + fn_preview.toString()+"------------15--------");
if (!f.exists() && !f_preview.exists()) {
try {
if (f.createNewFile())
return new String[] { dir + fn,
dir + fn_preview.toString() };
} catch (SecurityException e) {
} catch (IOException e) {
} finally {
f = null;
f_preview = null;
}
}
times++;
} while (times < 10);
return null;
}
/**
* 返回保存文件的物理路径
*
* @param ctx
* @return
*/
private String getUploadPath(HttpServletRequest context) {
if (upload_path != null){
System.out.println("----------1-----------"+upload_path+"---------1--------");
return upload_path;
}
String dir = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
System.out.println("----------2-----------"+dir+"---------2--------");
if (dir.startsWith("file://"))
upload_path = dir.substring("file://".length());
else if (dir.startsWith("/"))
upload_path = context.getSession().getServletContext().getRealPath(dir);
else
upload_path = dir;
if (!upload_path.endsWith(File.separator))
upload_path += File.separator;
System.out.println("------------3---------"+upload_path+"----------3-------");
return upload_path;
}
/**
* 返回文件对应的BaseURL
*
* @param ctx
* @return
*/
private String getPhotoBaseURI() {
if (upload_uri != null)
return upload_uri;
upload_uri = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
if (!upload_uri.endsWith("/"))
upload_uri += '/';
return upload_uri;
}
private String upload_path = null;
private String upload_uri = null;
}
这些就可以完成正常的上传下载的功能啦。
<%@ page contentType="text/html;charset=utf-8"%>
<%@ include file="/commons/taglibs.jsp"%>
<template:insert template="/commons/templates/form.jsp">
<!-- 指定标题 -->
<template:put name="title">项目文档信息编辑</template:put>
<!-- 指定head标签之间的附加内容-->
<template:put name="head">
<script language="javascript" src="${ctx}/scripts/datetimeSelect.js"
type="text/javascript"></script>
<script language="javascript" type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
//当表单提交时执行验证
var validator = $("#inputForm").validate( {
//表单提交的处理
submitHandler : function() {
//ajax提交表单 指定form名称和成功后跳转的地址
AjaxForm.submit("#inputForm",
"${ctx}/project/document/list.view");
}
});
if ("${action}".indexOf("insert") >= 0) {
//插入时
$("#file").focus();
}
});
function doExamine(id,state){
AjaxRequest.submit("examine.save", {
"id" : id,state:state
}, "${ctx}/project/document/list.view");
}
</script>
</template:put>
<!-- 指定表单内容 -->
<template:put name="form">
<!-- form的名称固定为mainForm -->
<form name="inputForm" id="inputForm" action="${action}" method="post"
enctype="multipart/form-data"><c:if
test="${sessionScope.employee.priv==1 && document.dataState!=1}">
<table class="form" cellspacing="1">
<tr>
<td width="120">资料截止日期<span class="notice">*</span></td>
<td width="300" class="special"><input type="text"
class="required text" name="endDate" id="endDate"
value="<c:out value="${document.endDate}"/>"
onclick="setDay(this);" /></td>
<td width="120">资料类型<span class="notice">*</span></td>
<td width="300" class="special"><select name="docType"
id="docType" title="请选择一个组" validate="required:true"
style="width: 152px;">
<option value="">请选择组</option>
<c:forEach items="${docTypes}" var="dt">
<c:choose>
<c:when test="${document.docType==dt}">
<option value="${dt}" selected="selected">${dt}</option>
</c:when>
<c:otherwise>
<option value="${dt}">${dt}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
</tr>
<tr>
<td>资料文档</td>
<td colspan="3"><input type="file" class="required text"
name="fileUpload" id="fileUpload" /></td>
</tr>
<tr>
<td colspan="4" align="left" height="50px"><c:if
test="${document.dataState==0 || document.dataState==3}">
<input type="submit" class="submit" value=" 保存 " />
</c:if> <input type="button" class="button" value="返回列表 "
onclick="window.location='${ctx}/project/document/list.view'" /></td>
</tr>
</table>
</c:if> <c:if
test="${sessionScope.employee.priv==2 || sessionScope.employee.priv==0 || (sessionScope.employee.priv==1 && document.dataState==1)}">
<table class="main" cellspacing="1">
<tr>
<td class="desc">资料截止日期</td>
<td width="300" class="special"><fmt:formatDate
value="${document.endDate}" type="date" dateStyle="long" /></td>
<td class="desc">资料类型</td>
<td width="300" class="special">${document.docType}</td>
</tr>
<tr>
<td class="desc">资料文档</td>
<td colspan="3"><a href="${ctx}/${document.document}">下载文档</a></td>
</tr>
<tr>
<td colspan="4" align="left" height="50px"><c:if
test="${document.dataState==1 && sessionScope.employee.priv==2}">
<input type="hidden" name="state" value="" id="state" />
<input type="button" class="button" value="审批通过 "
onclick="doExamine(${document.id},2);" />
<input type="button" class="button" value="审批不通过 "
onclick="doExamine(${document.id},3);" />
</c:if> <input type="button" class="button" value="返回列表 "
onclick="window.location='${ctx}/project/document/list.view'" />
</td>
</tr>
</table>
</c:if> <input type="hidden" name="id" value="${document.id} " /></form>
</template:put>
</template:insert>
下面是DocumentAction(采用spring的注释):
package com.ztev.fipmis.project;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import com.ztev.fipmis.BaseAction;
import com.ztev.fipmis.BaseService;
import com.ztev.fipmis.ServiceException;
import com.ztev.fipmis.SessionManager;
import com.ztev.fipmis.baseinfo.AdcdBean;
import com.ztev.fipmis.baseinfo.AdcdService;
import com.ztev.fipmis.baseinfo.EmployeeBean;
import com.ztev.fipmis.file.FileSystemSaver;
import com.ztev.fipmis.irrigation.util.AdcdIrUtil;
import com.ztev.pagination.PageParameterSimple;
/**
* 项目文档信息操作控制器。
*
* @author 朱志国 (zhu.zhiguo@hotmail.com) *
*/
@Controller
@RequestMapping("/project/document/")
public class DocumentAction extends BaseAction {
@InitBinder
public void initBinder(WebDataBinder binder){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
binder.registerCustomEditor(Date.class,new CustomDateEditor(format, true));
}
/**
* 项目文档处理业务实例
*/
@Autowired
private DocumentService documentService;
@Autowired
private AdcdService adcdService;
/**
* 显示列表,默认页面
*
* @param model
* @param pp
* 分页参数。
* @param user
* 查询条件
* @return
*/
@RequestMapping("list.view")
public String showList(Model model, PageParameterSimple pp,
Document document,HttpSession session,AdcdBean queryBean) {
//请求为空
if( StringUtils.isBlank(queryBean.getAdcd()) ){
/** 取得用户上次查询的行政区划信息**/
AdcdBean adcdBean = SessionManager.getQueryAdcdBean(session);
/** 上次查询的行政区划信息为空,使用当前权限默认查询**/
if( adcdBean == null ){
//查找当前权限下所有Adcd
EmployeeBean user = SessionManager.getEmployee(session);
//找到当前权限默认查询
BeanUtils.copyProperties(user, queryBean);
}else{
BeanUtils.copyProperties(adcdBean, queryBean);
}
}else{
/** 保存用户查询的行政区划信息**/
SessionManager.setQueryAdcdBean(session, queryBean);
}
//默认选中行政条件
model.addAttribute("queryAdcd", queryBean);
//用户查询行政区划
List<AdcdBean> rightAdcdBeans = adcdService.findListBylike(queryBean.getAdcd());
// 分页信息,名字固定为pageinfo
model.addAttribute("pageinfo", this.documentService.findPage(pp,
document,AdcdIrUtil.getAdcdsCodeStr(rightAdcdBeans)));
model.addAttribute("documentQuery", document);
return "project/document/documentList";
}// end showList
/**
* 显示插入表单
*
* @param model
* @return
*/
@RequestMapping("insert.form")
public String showInsert(Model model) {
Document document = new Document();
document.setDataState(0);
model.addAttribute("docTypes", BaseService.findAllDocType());
model.addAttribute("document", document);
model.addAttribute("action", "insert.save");
model.addAttribute("groups", "");
return "project/document/documentForm";
}// end showInsert
/**
* 显示修改页面
*
* @param userId
* 用户唯一标识。
* @param model
* @return
*/
@RequestMapping("update.form")
public String showUpate(@RequestParam("id") Integer documentId,
HttpSession session, Model model) {
Document document = this.documentService.find(documentId);
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
if (user.getPriv() == 2) {
model.addAttribute("action", "examine.save");
} else if (user.getPriv() == 1) {
model.addAttribute("action", "update.save");
}
model.addAttribute("docTypes", BaseService.findAllDocType());
model.addAttribute("document", document);
model.addAttribute("action", "update.save");
model.addAttribute("groups", "");
return "project/document/documentForm";
}// end showUpate
/**
* 执行插入
*
* @param user
* @return
*/
@RequestMapping("insert.save")
public void saveInsert(Document document, HttpServletResponse response,
DefaultMultipartHttpServletRequest request,HttpSession session) throws Exception {
MultipartFile multipartFile = document.getFileUpload();
FileSystemSaver saver = new FileSystemSaver();
Document docut = saver.save(multipartFile,request);
document.setDocument(docut.getDocument());
document.setName(docut.getName());
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
document.setInputTime(new Date(System.currentTimeMillis()));
document.setAdcd(user.getAdcd());
document.setDataState(0);
document.setInputEmpNo(user.getEmpNo());
try {
this.documentService.insert(document);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveInsert
@RequestMapping("download.view")
public void showdDwnload(@RequestParam("id") Integer id,HttpServletResponse response,HttpServletRequest request) throws Exception {
Document document = documentService.find(id);
try {
//document.setDocument(request.getRequestURL().toString().replaceAll(request.getRequestURI(), "")+ request.getContextPath()+document.getDocument());
FileSystemSaver saver = new FileSystemSaver();
saver.download(response, document,request);
} catch (ServiceException se) {
}
}// end saveInsert
/**
* 执行更新。
*
* @param user
* @return
*/
@RequestMapping("update.save")
public void saveUpdate(Document document, HttpServletResponse response,
DefaultMultipartHttpServletRequest request) throws Exception {
MultipartFile multipartFile = document.getFileUpload();
FileSystemSaver saver = new FileSystemSaver();
if (multipartFile!=null) {
Document docut = saver.save(multipartFile,request);
document.setDocument(docut.getDocument());
}
this.documentService.update(document);
super.printJson(response, true);
}// end saveUpdate
/**
* 执行更新。
*
* @param userId
* 用户唯一标识。
* @return
*/
@RequestMapping("delete.save")
public void saveDelete(Integer id, HttpServletResponse response,HttpServletRequest request)
throws Exception {
try {
String url=documentService.find(id).getDocument();
this.documentService.delete(id);
FileSystemSaver saver = new FileSystemSaver();
saver.delete(url, request);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveDelete
/**
* 提交审批。
*
* @param userId
* 用户唯一标识。
* @return
*/
@RequestMapping("examine.save")
public void saveExamine(@RequestParam("id") Integer id,
@RequestParam("state") Integer state, HttpServletResponse response,
HttpServletRequest request,HttpSession session) throws Exception {
try {
EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
Document document = documentService.find(id);
if (document.getDataState() == 0) {
document.setDataState(1);
} else {
document.setDataState(state);
document.setApproveTime(new Date(System.currentTimeMillis()));
document.setApproveEmpNo(user.getEmpNo());
}
this.documentService.examine(document);
super.printJson(response, true);
} catch (ServiceException se) {
super.printJson(response, false, se.getMessage());
}
}// end saveDelete
}
以下是DocumentService:
package com.ztev.fipmis;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 业务操作的基类。
*
* @朱志国 (zhu.zhiguo@hotmail.com) *
*/
public class BaseService {
/**资金类别(来源)的类型标识*/
public static final String TYPE_DOC_TYPE = "document-type";
/**建设属性*/
public static final String IRBUILD_BEAN= "irbuild-bean";
/** 投资部门分类*/
public static final String INVERT_DEPT= "invest-Dept";
/**
* 日志操作句柄
*/
protected Log logger = LogFactory.getLog(getClass());
public static String[] findAllDocType(){
return BaseDataHelper.getValues(TYPE_DOC_TYPE);
}
public static Map<String, String> findIrbuildDec(){
return BaseDataHelper.getKeyDescriptionMap(IRBUILD_BEAN);
}
public static Map<String, String> findIrbuildValue(){
return BaseDataHelper.getKeyValueMap(IRBUILD_BEAN);
}
public static String[] findInvestDepart(){
return BaseDataHelper.getValues(INVERT_DEPT);
}
public static Map<String, String> findInvDepDscription(){
return BaseDataHelper.getKeyDescriptionMap(INVERT_DEPT);
}
public static BaseDataEntry[] findAllInvertDept(){
return BaseDataHelper.getEntries(INVERT_DEPT);
}
public static Map<String, String> findInvertDeptValue(){
return BaseDataHelper.getKeyValueMap(INVERT_DEPT);
}
}
以下是 FileSystemSaver :
package com.ztev.fipmis.file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import com.ztev.fipmis.ConfigManager;
import com.ztev.fipmis.StringUtils;
import com.ztev.fipmis.project.Document;
/**
* 将文档保存在文件系统中
*
* @author 李飞飞
*/
public class FileSystemSaver {
/**
* 判断该类型文件是否允许上传
*
* @param file
* @return
*/
protected boolean accept(String fileName) {
String filesDenied = ConfigManager.getProperty(ConfigManager.KEY_FILES_DENIED);
if (filesDenied == null)
return true;
StringTokenizer st = new StringTokenizer(filesDenied, ",");
while (st.hasMoreElements()) {
if (fileName.equalsIgnoreCase(st.nextToken()))
return false;
}
return true;
}
/**
* 下载文件方法
* @param response
* @param path 文件地址
* @param name 文件名
* @throws IOException
*/
public void download(HttpServletResponse response,Document document,HttpServletRequest request) throws IOException{
String fileName = new String(document.getName().getBytes("GBK"),"ISO8859-1");
response.setContentType( document.getDocType() ); //或gif等
response.setHeader("Content-Disposition", "attachment;filename=" +fileName);
//获取欲下载的文件输入流
String uploadPath = this.getUploadPath(request);
String baseURI = this.getPhotoBaseURI();
String path=uploadPath+ StringUtils.replace(document.getDocument().substring(baseURI.length()), "/",File.separator);
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
FileCopyUtils.copy(bis, response.getOutputStream());
response.getOutputStream().flush();
response.getWriter().flush();
response.getWriter().close();
}
/**
* 保存文件方法
*
* @param imgFile
* @param fileName
* @param autoRotate
* @param context
* @return
* @throws IOException
*/
@SuppressWarnings("null")
public Document save(MultipartFile file, DefaultMultipartHttpServletRequest request)
throws IOException {
Document document = new Document();
System.out.println("-----------得到文件名称--------"+file.getOriginalFilename()+"---------4--------");
//file.getOriginalFilename()得到文件名称(加后缀)而 getFileExtend得到文件的后缀名
String extendName = getFileExtend(file.getOriginalFilename());
System.out.println("-----------得到文件--------"+extendName+"---------6--------");
String[] urls = this.createNewPhotoURI(extendName, request);
if (urls == null && urls.length == 0)
return null;
String origionalPath = urls[0];
System.out.println("-----------7--------"+origionalPath+"---------7--------");
// 保存上传的文件
{
writeToFile(file, origionalPath);
}
// 计算图片的url
String uploadPath = this.getUploadPath(request);
System.out.println("------------5-----------"+uploadPath+"------------5--------");
//得到图片在文件夹的完整名称
String path = origionalPath.substring(uploadPath.length());
System.out.println("------------6-----------"+path+"------------6--------");
document.setDocument(getPhotoBaseURI()+ StringUtils.replace(path, File.separator, "/"));
System.out.println("------------8-----------"+getPhotoBaseURI()+"------------8--------");
document.setDocType(extendName);
document.setName(file.getOriginalFilename());
System.out.println("------------9-----------"+file.getOriginalFilename()+"------------9--------");
System.out.println(document.getDocument());
return document;
}
/**
* 判断是否为合法的文档
*
* @param extendName
* @return
*/
public static boolean isImage(String extendName) {
return "doc".equalsIgnoreCase(extendName)
|| "rar".equalsIgnoreCase(extendName)
|| "xls".equalsIgnoreCase(extendName)
|| "ppt".equalsIgnoreCase(extendName)
|| "txt".equalsIgnoreCase(extendName)
|| "pdf".equalsIgnoreCase(extendName);
}
/**
* 获取文件类型
* @param fn
* @return
*/
public String getFileExtend(String fn){
if(StringUtils.isEmpty(fn))
return null;
int idx = fn.lastIndexOf('.')+1;
if(idx==0 || idx >= fn.length())
return null;
return fn.substring(idx);
}
/**
* 将上传的保存到磁盘中
* 文件
* @param imgFile
* @param origionalPath
* @throws IOException
*/
public static void writeToFile(MultipartFile multifile, String origionalPath)
throws IOException {
File file=new File(origionalPath);
// 保存上传的文件
FileUtils.writeByteArrayToFile(file,multifile.getBytes());
}
/*
* (non-Javadoc)
*
* @see com.liusoft.dlog4j.photo.PhotoSaver#delete(java.lang.String)
*/
public boolean delete(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return f.delete();
return false;
}
/**
* 检测与创建一级、二级文件夹、文件名 这里我通过传入的两个字符串来做一级文件夹和二级文件夹名称
* 通过此种办法我们可以做到根据用户的选择保存到相应的文件夹下
*/
public File creatFolder(String typeName, String brandName, String fileName) {
File file = null;
typeName = typeName.replaceAll("/", ""); // 去掉"/"
typeName = typeName.replaceAll(" ", ""); // 替换半角空格
typeName = typeName.replaceAll(" ", ""); // 替换全角空格
brandName = brandName.replaceAll("/", ""); // 去掉"/"
brandName = brandName.replaceAll(" ", ""); // 替换半角空格
brandName = brandName.replaceAll(" ", ""); // 替换全角空格
File firstFolder = new File("c:/" + typeName); // 一级文件夹
if (firstFolder.exists()) { // 如果一级文件夹存在,则检测二级文件夹
File secondFolder = new File(firstFolder, brandName);
if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
file = new File(secondFolder, fileName);
} else { // 如果二级文件夹不存在,则创建二级文件夹
secondFolder.mkdir();
file = new File(secondFolder, fileName); // 创建完二级文件夹后,再合建文件
}
} else { // 如果一级不存在,则创建一级文件夹
firstFolder.mkdir();
File secondFolder = new File(firstFolder, brandName);
if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
file = new File(secondFolder, fileName);
} else { // 如果二级文件夹不存在,则创建二级文件夹
secondFolder.mkdir();
file = new File(secondFolder, fileName);
}
}
return file;
}
public InputStream read(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return new FileInputStream(f);
return null;
}
public OutputStream write(String imgURL, HttpServletRequest context)
throws IOException {
String uploadPath = this.getUploadPath(context);
String baseURI = this.getPhotoBaseURI();
String path = uploadPath
+ StringUtils.replace(imgURL.substring(baseURI.length()), "/",
File.separator);
File f = new File(path);
if (f.exists() && f.isFile())
return new FileOutputStream(f, false);
return null;
}
/**
* 生成一个用于存储文件并返回其URI地址
*
* @param ctx
* @param ext
* 例如: .gif
* @return
* @throws IOException
*/
private String[] createNewPhotoURI(String ext, HttpServletRequest context)
throws IOException {
Calendar cal = Calendar.getInstance();
StringBuffer dir = new StringBuffer();
dir.append(getUploadPath(context));
System.out.println("------------10-----------"+getUploadPath(context)+"------------10--------");
dir.append(cal.get(Calendar.YEAR));
System.out.println("------------11-----------"+dir.toString()+"------------11--------");
dir.append(File.separator);
System.out.println("------------12-----------"+dir.toString()+"------------12--------");
dir.append(cal.get(Calendar.MONTH) + 1);
dir.append(File.separator);
dir.append(cal.get(Calendar.DATE));
dir.append(File.separator);
System.out.println("------------13-----------"+dir.toString()+"------------13--------");
File file = new File(dir.toString());
if (!file.exists()) {
// 如果目录不存在则创建目录
synchronized (FileSystemSaver.class) {
if (!file.mkdirs())
return null;
}
}
file = null;
int times = 0;
do {
// 生成独一无二的文件名
String fn = String.valueOf(System.currentTimeMillis()) + '.' + ext;
System.out.println("------------14-----------"+fn+"------------14--------");
StringBuffer fn_preview = new StringBuffer();
fn_preview.append(System.currentTimeMillis());
fn_preview.append("_s.");
fn_preview.append(ext);
File f = new File(dir + fn);
File f_preview = new File(dir + fn_preview.toString());
System.out.println("------------15-----------"+dir + fn_preview.toString()+"------------15--------");
if (!f.exists() && !f_preview.exists()) {
try {
if (f.createNewFile())
return new String[] { dir + fn,
dir + fn_preview.toString() };
} catch (SecurityException e) {
} catch (IOException e) {
} finally {
f = null;
f_preview = null;
}
}
times++;
} while (times < 10);
return null;
}
/**
* 返回保存文件的物理路径
*
* @param ctx
* @return
*/
private String getUploadPath(HttpServletRequest context) {
if (upload_path != null){
System.out.println("----------1-----------"+upload_path+"---------1--------");
return upload_path;
}
String dir = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
System.out.println("----------2-----------"+dir+"---------2--------");
if (dir.startsWith("file://"))
upload_path = dir.substring("file://".length());
else if (dir.startsWith("/"))
upload_path = context.getSession().getServletContext().getRealPath(dir);
else
upload_path = dir;
if (!upload_path.endsWith(File.separator))
upload_path += File.separator;
System.out.println("------------3---------"+upload_path+"----------3-------");
return upload_path;
}
/**
* 返回文件对应的BaseURL
*
* @param ctx
* @return
*/
private String getPhotoBaseURI() {
if (upload_uri != null)
return upload_uri;
upload_uri = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
if (!upload_uri.endsWith("/"))
upload_uri += '/';
return upload_uri;
}
private String upload_path = null;
private String upload_uri = null;
}
这些就可以完成正常的上传下载的功能啦。
评论
1 楼
mj37yhyy
2010-08-02
你好!
我在用Spring3下载的时候出现了问题,请帮我解决一下:
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
代码如下:
/**
* 下载至本地
*
* @param id
* @param path
* @return
*/
@RequestMapping(value = "/downloadToStream")
// public @ResponseBody ModelAndView
// downloadToStream(@RequestParam("fileid") String id,
public ModelAndView downloadToStream(@RequestParam("fileid") String id,
HttpServletRequest request, HttpServletResponse response
// ,@ModelAttribute("sessionMng") SessionMng sessionMng
// ,@RequestBody Userinfo userinfo
) {
Fileupload fileupload = null;
if (id != null && !id.equals(""))
fileupload = fileUploadService.findById(new Long(id).longValue());
ServletOutputStream os = null;
try {
response.reset();
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment; filename="
+ fileupload.getFilename());
// InputStream fis = new InputStream();
// BufferedInputStream bis = new
// BufferedInputStream(fileupload.getFiledata());
FileCopyUtils.copy(fileupload.getFiledata(), response
.getOutputStream());
response.getOutputStream().flush();
response.flushBuffer();
// response.getWriter().flush();
// response.getWriter().close();
// os = response.getOutputStream();
// os.write(fileupload.getFiledata());
} catch (Exception e1) {
e1.printStackTrace();
}
// finally {
// if(os != null)
// try {
// os.flush();
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
return new ModelAndView("/allocation/fileoperate/filedownload.jsp");
}
我在用Spring3下载的时候出现了问题,请帮我解决一下:
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
代码如下:
/**
* 下载至本地
*
* @param id
* @param path
* @return
*/
@RequestMapping(value = "/downloadToStream")
// public @ResponseBody ModelAndView
// downloadToStream(@RequestParam("fileid") String id,
public ModelAndView downloadToStream(@RequestParam("fileid") String id,
HttpServletRequest request, HttpServletResponse response
// ,@ModelAttribute("sessionMng") SessionMng sessionMng
// ,@RequestBody Userinfo userinfo
) {
Fileupload fileupload = null;
if (id != null && !id.equals(""))
fileupload = fileUploadService.findById(new Long(id).longValue());
ServletOutputStream os = null;
try {
response.reset();
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment; filename="
+ fileupload.getFilename());
// InputStream fis = new InputStream();
// BufferedInputStream bis = new
// BufferedInputStream(fileupload.getFiledata());
FileCopyUtils.copy(fileupload.getFiledata(), response
.getOutputStream());
response.getOutputStream().flush();
response.flushBuffer();
// response.getWriter().flush();
// response.getWriter().close();
// os = response.getOutputStream();
// os.write(fileupload.getFiledata());
} catch (Exception e1) {
e1.printStackTrace();
}
// finally {
// if(os != null)
// try {
// os.flush();
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
return new ModelAndView("/allocation/fileoperate/filedownload.jsp");
}
相关推荐
《Spring 3.0、Spring MVC 3.0与MyBatis 3.0整合详解》 在现代Java企业级应用开发中,Spring框架因其强大的功能和灵活性而被广泛使用。Spring 3.0作为其重要的一个版本,引入了诸多改进和新特性,提升了开发效率和...
Spring MVC 3.0是Spring框架的一个重要组成部分,专门用于构建Web应用程序的模型-视图-控制器(MVC)...通过分析和运行这些示例,可以更好地掌握Spring MVC 3.0与Hibernate、Interceptor、AOP注解和EHcache的集成应用。
- **MVC框架**:在Spring MVC等框架中,文件上传和下载的处理更加简洁,框架提供了专门的注解和处理器。 4. **源代码分析** - `FileDownLoad`:这个文件可能是用于处理文件下载逻辑的Java类。可能包含一个Servlet...
- 项目中提供了多数据源使用的示例代码和配置方法,方便开发者根据实际业务需求进行调整。 - **3.3 源码讲解** - 详细介绍了多数据源的实现原理和配置过程,帮助开发者更好地理解其内部工作机制。 #### 四、基础...
国内第一本基于spring3.0的著作,从源代码的角度对spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从木书中参透spring框架的优秀架构和设计思想,而且还能从spring优雅的实现源码...
- 一个标准的SpringBoot项目通常包括`src/main/java`下的`main`和`test`目录,分别存放主代码和测试代码。`main`下可能有`com.example.ExcelDemo`这样的包结构,包含配置类、控制器、服务类、DAO类等。 - 压缩包中...
5. **源代码下载**:提供的"**WbFile**"可能是源代码示例,它包含了如何配置CXF和Spring以实现文件传输的实例。分析和学习这个代码可以帮助你理解具体实现细节,如服务的定义、文件操作的处理等。 总的来说,结合...
1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合...
3. **文档管理系统**:OA系统通常包含强大的文档管理功能,如文档上传、下载、版本控制、权限设置等。通过源码,我们可以研究如何实现高效、安全的文档存储和协作机制。 4. **数据库设计**:源码中会涉及到与数据库...
这是一个基于Java技术栈的OA(Office Automation)办公自动化管理系统,主要使用了Struts1.2作为MVC框架,Hibernate3.0作为持久层框架,Spring2进行依赖注入和事务管理,而DWR(Direct Web Remoting)则用于实现前端...
- `src/main/java`:包含所有Java源代码,如控制器(Controller)、服务(Service)、模型(Model)和DAO(Data Access Object)层的类。 - `src/main/resources`:存放配置文件,如Spring的XML配置文件,可能包括...
Struts+Spring+Hibernate实现上传下载 本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。SSH各框架的均为当前最新版本: •Struts 1.2 •Spring 1.2.5 •Hibernate 3.0 本文...
- 解压“文件上传和下载jar包”,查看类库文档或源代码,了解具体用法。 - 引入库到项目中,根据API实现文件上传和下载功能。 这个“文件上传和下载jar包”可能封装了上述的一些功能,简化了开发过程。使用时,...
2. **Spring Expression Language (SpEL)**:这是Spring 3.0引入的一个强大表达式语言,用于在运行时查询和操作对象图。在3.2版本中,SpEL进一步得到增强,使得开发者能够更灵活地进行数据绑定和表达式评估。 3. **...
、Struts2、Spring3.0、Hibernate3.3等技术编写的源代码。 整个项目采用MVC模式,应用Struts Spring Hibernate三个框架实现了一个小区管理系统。分为View层(显示层)、Control层(控制层)、Service层(业务逻辑层...
Spring 的主要特点在于其轻量级特性,基础版本仅约2MB,以及它所实现的控制反转(IOC)和面向切面编程(AOP)原则,这使得代码更加灵活且易于维护。 1. **控制反转(IOC)**:在Spring框架中,IOC意味着对象的创建...
【标题】:“[电子商务]网龙java版仿阿里巴巴b2b平台 v3.0_wl-b2b.rar”指的是一个基于Java技术开发的电子商务系统,该系统模仿了阿里巴巴B2B(Business-to-Business)平台的功能和用户体验。网龙公司是一家知名的...
1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合...
尽管“全站代码”标签暗示了该文件可能包含整个应用的源代码,但在此我们将重点讨论这款应用的核心功能和可能的实现技术。 首先,同学录的核心功能包括: 1. 学生信息管理:这是最基本的功能,允许用户输入、编辑...
升级了3.0版本的一下内容: 增加了在线支付接口功能 增加了忘记密码邮件找回功能 增加了邮件激活功能 增强了前台页面的用户友好性 框架:struts2+spring2.5+hibernate3.2+jsp+jquery1.3+mysql5.0 主要功能:...