直接上代码和导入的包,修修改改就可使用,大同小异
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
@Controller
public class RequirementManageAction extends CommonAction {
private IRequirementManageService requirementManageService;
private IRequirementFileService requirementFileService;
private File[] files;//文件上传信息
private String[] filesFileName;
private String[] filesContentType;
public void setRequirementFileService(IRequirementFileService requirementFileService) {
this.requirementFileService = requirementFileService;
}
public void setRequirementManageService(IRequirementManageService requirementManageService) {
this.requirementManageService = requirementManageService;
}
/**
* 分页信息查询需求管理 例子: basepath + "base/querylist_requirementManage.action"
*
* @throws Exception
*/
public String querylist() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
Map map = this.requestDataToMap();
if (map.get("tagId") != null && !StringUtil.isEmpty(map.get("tagId").toString())) {
map.put("tagId", SqlUtil.getInSql(map.get("tagId").toString()));
}
map.put("condition", SqlUtil.makeCondition2Sql(map));
Page page = requirementManageService.getListForPage(map, pagesize, pagerow, sort, dir);
// TagsDataUtil.getDatasTags("18", page, "rmId");
Map dicMap = new HashMap();
dicMap.put("busiTypeName", "busiType");
dicMap.put("priorityName", "priority");
dicMap.put("statusName", "req_status");
DictUtil.CodeToName(page.getData(), dicMap);
this.setResult(new BusinessResult(true, "200", page.getData(), page.getTotalRows()));
return "success";
}
/**
* 需求管理单条信息查询 例子: basepath + "base/query_requirementManage.action"
*
* @throws Exception
*/
public String query() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
RequirementManage queryEntity = (RequirementManage) requestDataToEntity(RequirementManage.class);
RequirementManage entity = requirementManageService.get(queryEntity);
RequirementFile requirementFile = new RequirementFile();
requirementFile.setRmId(queryEntity.getRmId());
List<RequirementFile> list = requirementFileService.getList(requirementFile);
entity.setRequirementFiles(list);
List li = new ArrayList();
li.add(entity);
this.setResult(new BusinessResult(true, "200", li));
return "success";
}
/**
* 通过文件id下载文件
* @return
* @throws Exception
*/
public String getFileById() throws Exception{
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
RequirementFile entity = (RequirementFile) requestDataToEntity(RequirementFile.class);
RequirementFile requirementFile = new RequirementFile(entity.getRfId());
entity.setWhere(requirementFile);
RequirementFile file = requirementFileService.get(entity);
HttpServletResponse response = ServletActionContext.getResponse();//获取响应对象
HttpServletRequest request = ServletActionContext.getRequest();
// 获取文件绝对路径
String realPath = getRequest().getServletContext().getRealPath("");//拼接文件路径
String filePath = file.getFilePath();
String replace = filePath.replace(getRequest().getContextPath()+"/", "");
filePath = realPath + replace;
// 获取文件名
// String filename = filePath.substring(filePath.lastIndexOf("_") + 1);
String filename = file.getFileName();
// 设置响应头信息
// String fileType = ServletActionContext.getServletContext().getMimeType(filename);
response.setHeader("Content-Type", file.getFileType());
// 解决乱码
String header = request.getHeader("User-Agent");
if (header.contains("Firefox")) {
byte[] bytes = filename.getBytes("UTF-8");
filename = new String(bytes,"ISO-8859-1");
} else {
filename =URLEncoder.encode(filename, "utf-8");
}
// 响应下载
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
// 创建流
InputStream is = new FileInputStream(filePath);
OutputStream os = response.getOutputStream();
// 输入流与输出流对接
int len = 0;
byte[] b = new byte[2048];
while ((len = is.read(b)) !=-1) {
os.write(b, 0, len);
}
os.close();
is.close();
return NONE;
}
/**
* 添加需求管理数据 例子: basepath + "base/insert_requirementManage.action"
*
* @throws Exception
*/
public String insert() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
RequirementManage entity = (RequirementManage) this.requestDataToEntity(RequirementManage.class);
entity.setRmId(UuidKey.getInstance().genKey());
entity.setCreateUserId(LoginUserUtil.getUserId());
entity.setCreateUserName(LoginUserUtil.getUserName());
entity.setCreateTime(new Date());
entity.setModifyUserId(LoginUserUtil.getUserId());
entity.setModifyUserName(LoginUserUtil.getUserName());
entity.setModifyTime(new Date());
requirementManageService.insert(entity);
Map<String, Object> map = null;
if(files != null && files.length > 0){
// 上传文件信息
map = uploadFiles(entity,null,null,null);
}
this.setResult(new BusinessResult(true, "success", map));
return "success";
}
/**
* 上传文件和文件信息
* @param entity
* @return
* @throws Exception
*/
public Map<String, Object> uploadFiles(RequirementManage entity, String busiType, String rmId,List<String> repeatFileName) throws Exception{
Map<String, Object> map = new HashMap<>();
// 上传文件
List<RequirementFile> listfile = new ArrayList<RequirementFile>();
// 判断数组是否有重复文件名
List<String> repeatName = checkRepeat(filesFileName);
if (repeatFileName != null && repeatFileName.size() > 0) {
repeatName.addAll(repeatFileName);
}
for(int i = 0; i < filesFileName.length; i++){
File file = files[i];
String filenamestr = filesFileName[i];
String fileType = filesContentType[i];
//重复了的文件不添加,跳过本次循环
if (repeatName != null && repeatName.size() > 0 && repeatName.contains(filenamestr)) {
continue;
}
// 拼接保存文件目录(表名作为子目录)
String path = null;
String realPath = getRequest().getServletContext().getRealPath("");
realPath = realPath.substring(0, realPath.indexOf("webapps")) + "webapps";
// String realPath = System.getProperty("catalina.home")+"/";
// String contextPath = getRequest().getContextPath();
// if (rmId != null && busiType != null) {
// // 需要更新
// path = "upload/" + BusiTypeEnum.getTableNameByCode(busiType);
// }else {
// path = "upload/" + BusiTypeEnum.getTableNameByCode(entity.getBusiType());
// }
if (rmId != null) {
// 这是更新
path = "/upload/" + rmId;
}else {
path = "/upload/" + entity.getRmId();
}
// 拼接新的文件名
// String filename = System.currentTimeMillis()+"_"+filenamestr;
File f = new File(realPath+path);
// 若目录不存在,创建
if(!f.exists() && !f.isDirectory()){
f.mkdirs();
}
try {
// 创建输出流和输入流
FileInputStream is = new FileInputStream(file);
FileOutputStream os = new FileOutputStream(realPath+path+"/"+filenamestr);
//流对拷
IOUtils.copy(is, os);
// 上传文件的信息
RequirementFile requirementFile = new RequirementFile();//上传文件信息
requirementFile.setRfId(UuidKey.getInstance().genKey());
if (rmId != null) {
// 这是更新
requirementFile.setRmId(rmId);
}else {
requirementFile.setRmId(entity.getRmId());
}
requirementFile.setFileType(fileType);
requirementFile.setFilePath(path+"/"+filenamestr);
requirementFile.setFileName(filenamestr);
listfile.add(requirementFile);
// 关闭资源
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
requirementFileService.insertBatch(listfile);
map.put("listfile", listfile);//上传成功的文件对象
map.put("repeatName", repeatName);//没有上传的重复文件名
return map;
}
/**
* 判断新增文件重复名
* @param filesFileName
* @return
*/
public List<String> checkRepeat(String[] filesFileName){
List<String> list = new ArrayList<>();
for (int i = 0; i < filesFileName.length - 1; i++) { // 循环开始元素
for (int j = i+1; j < filesFileName.length; j++) { // 循环后续所有元素
// 如果相等,则重复
if (filesFileName[i].equals(filesFileName[j])) {
list.add(filesFileName[i]);
break;
}
}
}
return list;
}
/**
* 修改需求管理数据 例子: basepath + "base/modify_requirementManage.action"
*
* @throws Exception
*/
public String modify() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
Map map = new HashMap();
map.put("requirementFiles", RequirementFile.class);
RequirementManage entity = (RequirementManage) JsonUtil.getDTOUnHandleEStr(data,RequirementManage.class, map);
if (StringUtils.isNotEmpty(entity.getRmId())) {
// 判断文件名是否已经存在
RequirementFile requirementFile = new RequirementFile();
requirementFile.setRmId(entity.getRmId());
List<RequirementFile> list = requirementFileService.getList(requirementFile);
List<String> repeatFileName = new ArrayList<>();
Map<String, Object> result = null;
// boolean flag = true;
if (list != null && list.size() > 0 && filesFileName != null && filesFileName.length > 0) {
for (RequirementFile file : list) {
for (int i = 0; i < filesFileName.length; i++) {
if (file.getFileName().equals(filesFileName[i])) {
// 该文件名已存在
// flag = false;
repeatFileName.add(filesFileName[i]);
break;
}
}
}
}
// if (flag) {
entity.setWhere(new RequirementManage(entity.getRmId()));
entity.setModifyUserId(LoginUserUtil.getUserId());
entity.setModifyUserName(LoginUserUtil.getUserName());
entity.setModifyTime(new Date());
requirementManageService.update(entity);//更新该需求信息
// 添加修改后的文件信息
if (files != null && files.length >0) {
result = uploadFiles(null,entity.getBusiType(),entity.getRmId(),repeatFileName);
}
// }
// if (repeatFileName != null && repeatFileName.size() > 0) {
// this.setResult(new BusinessResult(false, "文件名已存在!",repeatFileName));
// }else {
this.setResult(new BusinessResult(true, "success",result));
// }
} else {
this.setResult(new BusinessResult(false,
SysResourcesUtil.getResPropertyValue("config/messages/base_zh.properties", "paramError")));
}
return "success";
}
/**
* 删除需求管理数据 例子: basepath + "base/delete_requirementManage.action"
*
* @throws Exception
*/
public String delete() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
RequirementManage entity = (RequirementManage) requestDataToEntity(RequirementManage.class);
if (StringUtils.isNotEmpty(entity.getRmId())) {
// 将状态置为无效,5,同事删除该需求下的文件和文件信息
entity.setStatus("5");
entity.setWhere(new RequirementManage(entity.getRmId()));
requirementManageService.update(entity);
// 先删该需求下文件,再删文件信息
deleteFileById(entity.getRmId(),null);
this.setResult(new BusinessResult(true, "success"));
} else {
this.setResult(new BusinessResult(false,
SysResourcesUtil.getResPropertyValue("config/messages/base_zh.properties", "paramError")));
}
return "success";
}
/**
* 修改文件时,直接删除文件及文件信息
* @return
* @throws Exception
*/
public String deleteFileByRfId() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
Map map = requestDataToMap();
if (StringUtils.isNotEmpty(map.get("rfId").toString())) {
deleteFileById(null,map.get("rfId").toString());
this.setResult(new BusinessResult(true, "success"));
} else {
this.setResult(new BusinessResult(false,
SysResourcesUtil.getResPropertyValue("config/messages/base_zh.properties", "paramError")));
}
return "success";
}
/**
* 根据需求id删除该需求下的文件
* @return
*/
public boolean deleteFileById(String rmId,String rfId) throws Exception{
boolean flag = true;
try {
RequirementFile requirementFile = new RequirementFile();
if (rmId != null) {
//这是删除需求
requirementFile.setRmId(rmId);
}else if(rfId != null){
// 这是修改需要删除的文件
requirementFile.setRfId(rfId);
}
// 先删除服务器上文件
List<RequirementFile> list = requirementFileService.getList(requirementFile);
for (RequirementFile requireFile : list) {
String realPath = getRequest().getServletContext().getRealPath("");
realPath = realPath.substring(0, realPath.indexOf("webapps")) + "webapps";
String filePath = requireFile.getFilePath();
File file = new File(realPath+filePath);
if(file.exists() && file.isFile()){
file.delete();
}
}
// 再删文件信息
requirementFileService.delete(requirementFile);
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
/**
* 不分页查询需求管理 例子: basepath + "base/querylistNP_requirementManage.action"
*
* @throws Exception
*/
public String querylistNP() throws Exception {
if (StringUtils.isEmpty(data)) {
this.setData(jsonStr());
}
if (StringUtils.isEmpty(data)) {
this.setResult(new BusinessResult(false,
SysResourcesUtil.getResPropertyValue("config/messages/base_zh.properties", "paramError")));
} else {
RequirementManage entity = (RequirementManage) requestDataToEntity(RequirementManage.class);
List li = requirementManageService.getList(entity);
this.setResult(new BusinessResult(true, "200", li, li.size()));
}
return "success";
}
public File[] getFiles() {
return files;
}
public void setFiles(File[] files) {
this.files = files;
}
public String[] getFilesFileName() {
return filesFileName;
}
public void setFilesFileName(String[] filesFileName) {
this.filesFileName = filesFileName;
}
public String[] getFilesContentType() {
return filesContentType;
}
public void setFilesContentType(String[] filesContentType) {
this.filesContentType = filesContentType;
}
}
本文介绍了一个需求管理系统中涉及的需求管理操作流程,包括需求的增删改查、文件上传下载等功能实现方式,适用于Java Web开发环境。
1758

被折叠的 条评论
为什么被折叠?



