package com.java1234.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.stereotype.Controller;
import com.java1234.entity.QueryResult;
import com.java1234.entity.TuserTable;
import com.java1234.entity.UserTable;
import com.java1234.service.UserTableService;
import com.java1234.tool.MyJson;
import com.java1234.tool.ResponseUtil;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
public class UserTableAction extends ActionSupport implements ServletRequestAware {
@Resource
private UserTableService userTableService;
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private String tableName;
private File uploadfile;
public File getUploadfile() {
return uploadfile;
}
public void setUploadfile(File uploadfile) {
this.uploadfile = uploadfile;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
String path;
public String userId;
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
this.request = arg0;
this.path = arg0.getContextPath();
}
//HttpSession session = new HttpSession();
public void getUserTableByUserId() throws IOException {
userId = request.getParameter("userId");
String page = request.getParameter("page");
String rows = request.getParameter("rows");
//session.setAttribute("userId", userId);
request.getSession().setAttribute("userId", userId);
System.out.print("getUserTableByUserId**************"+request.getSession().getAttribute("userId"));
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
if (session.getAttribute("currentUser") == null) {
response.sendRedirect(path + "/user/user_login.action");
return;
}
response.setContentType("text/html;charset=utf-8");
QueryResult<TuserTable> tuserTable = userTableService.getTuserTableList(userId, Integer.parseInt(page),Integer.parseInt(rows));
List<TuserTable> tuserTableList = tuserTable.getList();
//System.out.print(userTable);
JSONObject result = new JSONObject();
JSONArray jsonArray = MyJson.getJSONArrayByList(tuserTableList);
Long total = tuserTable.getCount();
//System.out.print(jsonArray);
result.put("total", total);
result.put("rows", jsonArray);
// result.put("total", total);
try {
ResponseUtil.write(response, result);
} catch (Exception e) {
e.printStackTrace();
}
/*
* ObjectMapper mapper = new ObjectMapper();
* response.getWriter().println(mapper.writeValueAsString(userTable));
*/
}
public void cheackFile() {
HttpServletResponse response = ServletActionContext.getResponse();
Map<String, Object> data = new HashMap<String, Object>();
boolean result = Boolean.TRUE;
// 定义容器接收文件名
String uploadFileName = null;
try {
String brProjectPath = request.getSession().getServletContext().getRealPath("/");
uploadFileName = request.getParameter("uploadFileName");
// 文件保存路径
String filePath = brProjectPath + "mapimage\\" + uploadFileName;
File date = new File(filePath);
if (date.exists()) {
data.put("isExists", Boolean.TRUE);
data.put("fileMsg", "文件已存在!是否覆盖!");
} else {
data.put("isExists", Boolean.FALSE);
}
} catch (Exception e) {
// _logger.error (e.getMessage (), e);
result = Boolean.FALSE;
data.put("errorMsg", "文件上传失败!");
}
data.put("success", result);
String jsonStr = JSONObject.fromObject(data).toString();
try {
ResponseUtil.write(response, jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
// return jsonStr;
}
boolean result;
public Object uploadMapFile() throws Exception {
System.out.print("uploadMapFile**************"+request.getSession().getAttribute("userId"));
String userId = (String) request.getSession().getAttribute("userId");
result = Boolean.TRUE;
String savePath = request.getSession().getServletContext().getRealPath("") + "map";
// 文件保存路径
String saveUrl = request.getSession().getServletContext().getRealPath("") + "img";
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter out = null; // 输出流
try {
out = response.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
// 定义能上传的文件格式
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp,json");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");
extMap.put("json", "json");
extMap.put("pdf", "pdf");
// 最大的文件大小
long maxSize = 1000000;
response.setContentType("text/html; charset=UTF-8");
if (!ServletFileUpload.isMultipartContent(this.request)) {
return getError("请选择文件");
}
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
uploadDir.mkdirs();
// return getError("上传目录不存在");
}
if (!uploadDir.canWrite()) {
return getError("没有权利");
}
String dirName = this.request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
return getError("目录名不正确");
}
savePath += dirName + "\\";
saveUrl += dirName + "\\";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
/*
* SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); String
* ymd=sdf.format(new Date()); savePath+=ymd+"/"; saveUrl+=ymd+"/";
*/
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) this.request;
String fileName = wrapper.getFileNames("uploadfile")[0];
File file = wrapper.getFiles("uploadfile")[0];
//System.out.println(fileName + "++++++" + file);
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// System.out.println(fileExt);
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
return null; }
if (file.length() > maxSize) {
out.print(getError("上传文件大小超过限制"));
return null;
}
String newImgName = fileName;
/*
* String newImgName = sdf.format(new Date()) + "_" + new
* Random().nextInt(1000) + "." + fileExt;
* System.out.println("newImgName====="+newImgName);
*/
byte[] buffer = new byte[1024];
FileOutputStream fos;
// 获取内存中当前文件输入流
InputStream in;
try {
// fos = new FileOutputStream(savePath + "/" + newImgName);
fos = new FileOutputStream(savePath + "/" + fileName);
in = new FileInputStream(file);
int num = 0;
while ((num = in.read(buffer)) > 0) {
fos.write(buffer, 0, num);
}
in.close();
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject obj = new JSONObject();
/*beging saveUserTable*/
UserTable userTable = new UserTable();
userTable.setTableName(tableName);
userTable.setUserId(userId);
userTable.setLink(newImgName);
saveUserTable(userTable);
/*end*/
obj.put("success", result);
obj.put("error", 0);
//obj.put("url", saveUrl + "/" + newImgName);
obj.put("url", saveUrl + "/" + newImgName);
obj.put("resultMsg", newImgName + "上传成功!");
out.println(JSONObject.fromObject(obj).toString());
//String jsonStr = JSONObject.fromObject(obj).toString();
return null;
}
private void saveUserTable(UserTable userTable) {
// TODO Auto-generated method stub
this.userTableService.saveUserTalbe(userTable);
}
public void deleteUserTalbe() throws Exception{
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
if(session.getAttribute("currentUser")==null){
response.sendRedirect(path+"/user/user_login.action");
return;
}
response.setContentType("text/html;charset=utf-8");
String[] delIds = request.getParameterValues("delIds[]");
System.out.println("********delIds********"+delIds[0]);
int delNums= 0;
String [] str=delIds;
int [] num=new int[str.length];
for(int i=0;i<num.length;i++){
num[i]=Integer.parseInt(str[i]);
System.out.println("****************"+num[i]);
UserTable userTable= (UserTable) userTableService.findUserTableById(num[i]);
System.out.println("****************"+userTable);
userTableService.deleteUserTalbe(userTable);
delNums=num.length;
}
JSONObject result = new JSONObject();
if(delNums>0){
result.put("delNums", delNums);
result.put("success", true);
}
else{
result.put("errorMsg", "删除失败!");
}
ResponseUtil.write(response, result);
}
/**
* kindeditor错误报告
*
* @param message
* 错误原因
* @return
*/
private String getError(String message) {
result = Boolean.FALSE;
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
JSONObject obj = new JSONObject();
obj.put("success", result);
obj.put("error", 1);
obj.put("message", message);
obj.put("errorMsg", "文件上传失败!");
String jsonStr = JSONObject.fromObject(obj).toString();
return jsonStr;
}
}
标签:Hibernate4,String,EasyUI,request,Maven,new,put,import,response From: https://www.cnblogs.com/ycmn/p/18634077