首页 > 其他分享 >Struts2+Spring4+Hibernate4+Maven+EasyUI整合开发 员工管理系统

Struts2+Spring4+Hibernate4+Maven+EasyUI整合开发 员工管理系统

时间:2024-12-26 19:41:40浏览次数:4  
标签:Hibernate4 String EasyUI request Maven new put import response

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

相关文章

  • 导入maven依赖以后报红
    新建项目以后直接复制的依赖,但是刷新maven都不好使然后开始检查maven下的conf包下的setting.xml文件里的内容,然后看仓库地址配置的也是我自己的,<offline>false</offline>这个是默认的就可以,  offline:值为true/false,true表示构建系统在离线模式下执行,默认为false;这个没有......
  • Maven导入依赖过程中下载极其慢导致下载失败的解决办法
    首先右键打开Maven像这样-——————》然后点击opensettings.xml如果之前没有这个文件那么这里会显示“createsettings.xml”直接点就好了新建之后直接到这个文件里面去在这个文件里面添加上镜像就行了,阿里云的镜像非常好用,在哪里都好用,尤其是在下载破python库的时候嘎嘎......
  • 欲使用StringUtils,可以导入的maven依赖包
    欲使用StringUtils,可以导入的maven依赖包|Id|Title|DateAdded|SourceUrl|PostType|Body|BlogId|Description|DateUpdated|IsMarkdown|EntryName|CreatedTime|IsActive|AutoDesc|AccessPermission||-------------|-------------|-------------|......
  • Maven 构建配置文件
    构建配置文件是一系列的配置项的值,可以用来设置或者覆盖Maven构建默认值。使用构建配置文件,你可以为不同的环境,比如说生产环境(Production)和开发(Development)环境,定制构建方式。配置文件在pom.xml文件中使用activeProfiles或者profiles元素指定,并且可以通过各种方式触......
  • Maven 仓库
    在Maven的术语中,仓库是一个位置(place)。Maven仓库是项目中依赖的第三方库,这个库所在的位置叫做仓库。在Maven中,任何一个依赖、插件或者项目构建的输出,都可以称之为构件。Maven仓库能帮助我们管理构件(主要是JAR),它就是放置所有JAR文件(WAR,ZIP,POM等等)的地方。Maven仓库有......
  • 使用Maven打包javaagent.jar
    1、简介        javaagent 是Java1.5之后引入的新特性,其主要作用是在class被加载之前对其拦截,以插入我们的字节码。java1.5之前使用的是JVMTI(jvmtoolinterface)技术来实现对class的拦截,不过这个是用C++编写的,比如debug功能就是用这个技术实现的。2、jar......
  • maven
    什么是maven.Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的项目管理工具软件。maven通过一段描述可以构建和管理我们的项目的软件。为什么使用maven、maven再构建项目时,可以完成jar的管理和加载。上面引用jar非常麻烦,我们需要一一自己上网址......
  • 无法访问 Maven 3.8.1 http 仓库
    1.情景展示从git上面下载下来的项目,项目导包失败,具体报错信息如下:无法访问Maven3.8.1http仓库可能的解决方案:检查Mavensettings.xml是否不包含http仓库检查Mavenpom文件是否不包含http仓库 http://maven.aliyun.com/nexus/content/groups/public/在Mave......
  • ISDP002_Maven上_创建Maven项目
    信息系统开发实践|系列文章传送门课程概述Maven上_创建Maven项目Maven下_Maven项目依赖配置创建SpringBoot3项目Spring组件与自动装配ISDP逻辑架构设计1Maven安装配置Maven(发音[ˈmeɪvn])是一个项目管理工具,可以对Java项目进行自动化的构建和依赖管理。目前......
  • 利用Docker搭建maven私服
    步骤一:安装Docker和DockerCompose首先,确保您的系统已安装Docker和DockerCompose。推荐用包管理工具安装。避免依赖问题;特别注意:docker和docker-compose两个版本匹配步骤二:创建DockerCompose文件一定要注意文件夹权限!!!自定义目录下创建一个新文件,并将其命名为do......