pom.xml的配置-----------------------
web.xml的配置----------------------
config中jdbc.properties 配置---------
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tansuo
jdbc.username=root
jdbc.password=663558
upload.file=D://uploadfile
validationQuery=SELECT 1
config中log4j.properties配置--------------
# Global logging configuration
log4j.rootLogger=DEBUG,stdout
log4j.logger.com.iss=DEBUG,file,sql_html
log4j.logger.com.isoftstone=DEBUG,file,sql_html
log4j.logger.com.jolbox=ERROR,file,sql_html
log4j.logger.org.apache.axis=ERROR,file,sql_html
# SqlMap logging configuration...
log4j.logger.java.sql.Connection=ERROR
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sql.PreparedStatement=INFO
log4j.logger.java.sql.ResultSet=ERROR
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.stdout.Target=System.out
##########################
#log4j.appender.stdout.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.stdout.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n
# File output by days...
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.file=${catalina.base}/logs/yymgc-base.log
log4j.appender.file.MaxFileSize=20000KB
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n
# HTML output...
log4j.appender.sql_html=org.apache.log4j.RollingFileAppender
log4j.appender.sql_html.Threshold=DEBUG
log4j.appender.sql_html.file=${catalina.base}/logs/yymgc-base.html
log4j.appender.sql_html.MaxFileSize=5000KB
log4j.appender.sql_html.MaxBackupIndex=1
log4j.appender.sql_html.layout=org.apache.log4j.HTMLLayout
#log4j.appender.sql_html.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] - %m%n
spring中配置spring-context.xml配置文件------------------
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
spring中配置spring-mvc.xml-----------
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
utils中的工具包使用
BaseModel.java------------------
package com.bw.util;
public class BaseModel {
private int page;//当前页
private int rows;//每页几条
private int startIndex;//从第几条开始
private String keyword;//查询的关键字
private String beginTime;//开始时间
private String endTime;//介绍时间
private String order;//排序字段
private String desc;//排序方式
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getStartIndex() {
return (page-1)*rows;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
ConfigUtil.java----------------
package com.bw.util;
import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class ConfigUtil {
private static Resource resource = new ClassPathResource("config/jdbc.properties");
private static Properties props = null;
public static String get(String key){
if(props==null){
try {
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
return props.getProperty(key);
}
}
ExcelUtils.java--------------------
package com.bw.util;
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.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* poi操作excel
* @author Administrator
*/
public class ExcelUtils {
public static void main(String[] args) throws Exception {
// List
// for (int i=0;i<10;i++) {
// User us = new User();
// us.setName("张三"+i);
// us.setPhone(i+"11111111111");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// us.setCreate_time(sdf.format(new Date()));
// us.setUser_name(i+"[email protected]");
// list.add(us);
// }
// String columnNames[] = {"姓名","电话","时间","邮箱"};
// String columns[] = {"name","phone","create_time","user_name"};
// exportExcelByList("D:\\wang.xls", list, columnNames, columns, "用户信息");
String[][] mm = readexcell("D:\\wang.xls",1);
System.out.println(123);
}
/**
* 读取excel
* @param filepath 文件路径
* @param startrow 读取的开始行
* @Result 返回一个二维数组(第一维放的是行,第二维放的是列表)
* @throws Exception
*/
public static String[][] readexcell(String filepath,int startrow) throws Exception{
// 判断文件是否存在
File file = new File(filepath);
if (!file.exists()) {
throw new IOException("文件" + filepath + "W不存在!");
}
//获取sheet
Sheet sheet = getSheet(filepath);
String[][] content = getData(startrow, sheet);
return content;
}
/**
* 读取excel
* @param filepath 文件路径
* @param startrow 读取的开始行
* @Result 返回一个二维数组(第一维放的是行,第二维放的是列表)
* @throws Exception
*/
public static String[][] readexcellByInput(InputStream is,String fileName,int startrow) throws Exception{
//文件后缀
String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf("."));
//获取sheet
Sheet sheet = null;
if (".xls".equals(extension)) {//2003
//获取工作薄
POIFSFileSystem fs = new POIFSFileSystem(is);
sheet = new HSSFWorkbook(fs).getSheetAt(0);
} else if (".xlsx".equals(extension) || ".xlsm".equals(extension)) {
sheet = new XSSFWorkbook(is).getSheetAt(0);
} else {
throw new IOException("文件(" + fileName + "),无法识别!");
}
//获取表单数据
String[][] content = getData(startrow, sheet);
return content;
}
/**
* 获取表单数据
* wangyue
* @param startrow
* @param sheet
* @return
* 2018年4月26日下午2:25:43
*/
private static String[][] getData(int startrow, Sheet sheet) {
// 得到总行数
int rowNum = sheet.getLastRowNum()+1;
// 根据第一行获取列数
Row row = sheet.getRow(0);
//获取总列数
int colNum = row.getPhysicalNumberOfCells();
//根据行列创建二维数组
String[][] content = new String[rowNum-startrow][colNum];
String[] cols = null;
//通过循环,给二维数组赋值
for (int i = startrow; i < rowNum; i++) {
row = sheet.getRow(i);
cols = new String[colNum];
for (int j = 0; j < colNum; j++) {
//获取每个单元格的值
cols[j] = getCellValue(row.getCell(j));
//把单元格的值存入二维数组
content[i - startrow][j] =cols[j];
}
}
return content;
}
/**
* 根据表名获取第一个sheet
* @param path d:\\1213.xml
* @return 2003-HSSFWorkbook 2007-XSSFWorkbook
* @throws Exception
*/
public static Sheet getSheet(String file) throws Exception {
//文件后缀
String extension = file.lastIndexOf(".") == -1 ? "" : file.substring(file.lastIndexOf("."));
//创建输入流
InputStream is = new FileInputStream(file);
if (".xls".equals(extension)) {//2003
//获取工作薄
POIFSFileSystem fs = new POIFSFileSystem(is);
return new HSSFWorkbook(fs).getSheetAt(0);
} else if (".xlsx".equals(extension) || ".xlsm".equals(extension)) {
return new XSSFWorkbook(is).getSheetAt(0);
} else {
throw new IOException("文件(" + file + "),无法识别!");
}
}
/**
* 功能:获取单元格的值
*/
private static String getCellValue(Cell cell) {
Object result = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
// 在excel里,日期也是数字,在此要进行判断
if(HSSFDateUtil.isCellDateFormatted(cell)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = cell.getDateCellValue();
result = sdf.format(date);
}else{
DecimalFormat df=new DecimalFormat("#");
result=df.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR:
result = cell.getErrorCellValue();
break;
case Cell.CELL_TYPE_BLANK:
break;
default:
break;
}
}
return result.toString();
}
/**
* 导出 ---到固定文件目录
* 根据传入List数据集合导出Excel表格 生成本地excel
* @param file (输出流路径)d:\\123.xml
* @param list 任何对象类型的list(数据库直接查询出的)User(id,name,age,sex)
* @param columnNames(表头名称)(姓名、性别、年龄)
* @param columns (表头对应的列名)(name,sex,age)注意顺序
* @param sheetName(sheet名称)
*/
@SuppressWarnings("rawtypes")
public static void exportExcelByList(String file, List list,String[] columnNames, String[] columns, String sheetName) {
OutputStream fos =null;
try {
//获取输出流
fos= new FileOutputStream(file);
//创建工作薄HSSFWorkbook
HSSFWorkbook wb = new HSSFWorkbook();
//创建表单sheet
HSSFSheet sheet = wb.createSheet(sheetName);
//创建样式对象
HSSFCellStyle style = wb.createCellStyle(); // 样式对象
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
//创建行--表头
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < columnNames.length; i++) {
//创建列、单元格
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnNames[i]);
cell.setCellStyle(style);
}
//创建数据列
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
//创建行--数据
HSSFRow listRow = sheet.createRow(i + 1);
//循环列字段数组
for (int j = 0; j < columns.length; j++) {
//创建列
HSSFCell listCell = listRow.createCell(j);
//根据反射调用方法
Method m = o.getClass().getMethod("get" + upperStr(columns[j]));
String value = (String) m.invoke(o);
if (value != null) {
listCell.setCellValue(value);
listCell.setCellStyle(style);
} else {
listCell.setCellValue("");
listCell.setCellStyle(style);
}
sheet.autoSizeColumn(j+1, true);//自适应,从1开始
}
}
//把工作薄写入到输出流
wb.write(fos);
System.out.println("生成excel成功:"+file);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据传入List数据集合导出Excel表格 返回页面选择保存路径的excel
* @param response (响应页面)
* @param list 数据列表
* @param columnNames 表头
* @param columns 对应列名
* @param sheetName
* @param filename
*/
@SuppressWarnings("rawtypes")
public static void exportExcel(HttpServletResponse response,List list, String[] columnNames, String[] columns,String sheetName, String filename) {
OutputStream fos = null;
try {
//响应输出流,让用户自己选择保存路径
response.setCharacterEncoding("UTF-8");
response.reset();//清除缓存
response.setContentType("octets/stream");
response.addHeader("Content-Disposition", "attachment;filename="+ new String((filename).getBytes("UTF-8"), "iso8859-1")+ ".xls");
fos = response.getOutputStream();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
HSSFCellStyle style = wb.createCellStyle(); // 样式对象
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < columnNames.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnNames[i]);
cell.setCellStyle(style);
}
for (int i = 0; i < list.size(); i++) {
HSSFRow listRow = sheet.createRow(i + 1);
Object o = list.get(i);
for (int j = 0; j < columns.length; j++) {
HSSFCell listCell = listRow.createCell(j);
Method m = o.getClass().getMethod("get" + upperStr(columns[j]));
String value = (String) m.invoke(o);
if (value != null) {
listCell.setCellValue(value + "");
listCell.setCellStyle(style);
} else {
listCell.setCellValue("");
listCell.setCellStyle(style);
}
sheet.autoSizeColumn(j+1, true);//自适应,从1开始
}
}
wb.write(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 把输入字符串的首字母改成大写
*
* @param str
* @return
*/
private static String upperStr(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
/**
* 海量数据导出 100万以上
* wangyue
* @param response 直接响应到浏览器
* @param list 数据列表
* @param columnNames 表头数组
* @param columns 和表头数组对应的字段数组
* @param sheetName sheet表单名称
* @param filename 工作薄名称
* 2018年4月26日下午1:53:29
*/
public static void exportBigData(HttpServletResponse response,List list, String[] columnNames, String[] columns,String sheetName, String filename){
OutputStream os = null;
try {
response.setContentType("application/force-download"); // 设置下载类型
response.setHeader("Content-Disposition","attachment;filename=" + filename); // 设置文件的名称
os = response.getOutputStream(); // 输出流
SXSSFWorkbook wb = new SXSSFWorkbook(1000);//内存中保留 1000 条数据,以免内存溢出,其余写入 硬盘
//获得该工作区的第一个sheet
Sheet sheet1 = wb.createSheet(sheetName);
int excelRow = 0;
//标题行
Row titleRow = (Row) sheet1.createRow(excelRow++);
for (int i = 0; i < columns.length; i++) {
Cell cell = titleRow.createCell(i);
cell.setCellValue(columns[i]);
}
if (list!= null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
//明细行
Row contentRow = (Row) sheet1.createRow(excelRow++);
List
for (int j = 0; j < reParam.size(); j++) {
Cell cell = contentRow.createCell(j);
cell.setCellValue(reParam.get(j));
}
}
}
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
} // 关闭输出流
}
}
}
SystemInterceptor.java--------------
package com.bw.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 拦截器
*
* 内容描述 :
*
* 修改日期: 2016年7月1日 下午8:00:51
*
UploadAndDownloadUtil.java-----------
package com.bw.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
public class UploadAndDownloadUtil {
public static String upFile(MultipartFile file, HttpServletRequest req) {
//获取文件真实名称
String filename = file.getOriginalFilename();
//获取后缀
String affix = filename.substring(filename.lastIndexOf("."));
//获取文件路径
String path=ConfigUtil.get("upload.file");
String th="/image";
//根据文件路径,创建文件对象
File pfl = new File(path);
if(!pfl.exists()){
pfl.mkdirs();
}
String newFilename =path+"/"+UUID.randomUUID().toString()+affix;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String newFilename1 =path+"/"+sdf.format(new Date())+affix;
// file.getInputStream();//获取输入流
//把文件存放到d盘
try {
file.transferTo(new File(newFilename));
// file.transferTo(new File(newFilename1));
} catch (Exception e) {
e.printStackTrace();
}
newFilename = newFilename.replace(path,th );
return newFilename;
}
public static void downloadFile(HttpServletRequest request,HttpServletResponse response,String fileName,String url) throws Exception {
//获取文件路径
String realPath=ConfigUtil.get("upload.file");
String path = realPath.substring(realPath.lastIndexOf("/"));
String name=fileName;
// 文件全路径
url = url.replace(path,realPath);
// 下载文件名
response.setContentType(request.getServletContext().getMimeType(name));
//设置响应头文件,标识为文件下载类型,并附上文件的名称
response.setHeader("Content-Disposition", "attachment;filename="+name);
//对文件进行读取和存贮
InputStream is = new FileInputStream(url);
OutputStream os = response.getOutputStream();
byte[] flush = new byte[1024];
int len = 0;
while((len = is.read(flush))!=-1){
os.write(flush,0,len);
os.flush();
}
is.close();
}
}