码迷,mamicode.com
首页 > 编程语言 > 详细

java框架-Springmvc-quzrtz-jasperreport-pio-pdfbox-jedis

时间:2018-03-11 14:24:37      阅读:378      评论:0      收藏:0      [点我收藏+]

标签:desc   output   _id   sem   scheduler   mys   别人   window   tput   

  1  代码区

  技术分享图片技术分享图片

技术分享图片
package com.zhouwuji.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.management.ListenerNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;

import org.aspectj.util.FileUtil;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.jfree.io.FileUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhouwuji.pojo.Student;
import com.zhouwuji.pojo.User;
import com.zhouwuji.service.UserService;
import com.zhouwuji.util.JasperUtils;
import com.zhouwuji.util.JasperLocalUtils;
import com.zhouwuji.util.RandomParam;



/** 
 * Title: MyDemo<br> 
 * Description: 下载数据库中的建立信??br> 
 * Copyright: Copyright (c) 2018 <br> 
 * Create DateTime: 2018????4??下午3:38:26 <br>
 * @author lvlin
 */
@Controller
public class JasperReportController {
   
    @Resource
    private UserService userService;
    
    @RequestMapping("downloadpdf.do")
    public void previewPdf(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException{
        List<User> lists=userService.selectUser();
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("author", "张三");
         //下载文件的名字
        String defaultFilename="1111";
         //读入的jrxml文件的位置路径
        String resoureFilePath="report2.jasper";
        System.out.println("===="+resoureFilePath);
        JasperUtils.exportmain("pdf", resoureFilePath, params, lists, defaultFilename, null, request, response);
    }
    
    @RequestMapping("downloadword.do")
    public void previewword(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException{
        List<User> lists=userService.selectUser();
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("author", "张三");
        //下载文件的名字
        String defaultFilename="1111";
        //读入的jrxml文件的位置路径
        String resoureFilePath="report2.jasper";
        System.out.println("===="+resoureFilePath);
        JasperUtils.exportmain("word", resoureFilePath, params, lists, defaultFilename, null, request, response);
    }
    
    @RequestMapping("downloadhtml.do")
    public void previewhtml(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException{
        List<User> lists=userService.selectUser();
        String pageno=request.getParameter("pageno");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("author", "张三");
        //下载文件的名字
        String defaultFilename="1111";
        //读入的jrxml文件的位置路径
        String resoureFilePath="report2.jasper";
        System.out.println("===="+resoureFilePath);
        JasperUtils.exportmain("html", resoureFilePath, params, lists, defaultFilename, pageno, request, response);
    }
    @RequestMapping("downloadexcel.do")
    public void previewexcel(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException{
        List<User> lists=userService.selectUser();
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("author", "张三");
        //下载文件的名字
        String defaultFilename="1111";
        //读入的jrxml文件的位置路径
        String resoureFilePath="report2.jasper";
        System.out.println("===="+resoureFilePath);
        JasperUtils.exportmain("excel", resoureFilePath, params, lists, defaultFilename, null, request, response);
    }    
}
JasperReportController
技术分享图片
package com.zhouwuji.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhouwuji.pojo.User;
import com.zhouwuji.service.UserService;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping("/login.do")
    @ResponseBody
    public String indexTest(HttpServletRequest request){
        System.out.println("=================="+request.getServletContext().getRealPath("/"));
        //userService.insert(new User("李四", "123456"));
        return  "success";
    }
    @RequestMapping("/select.do")
    @ResponseBody
    public List<User> selectString(){
        List<User> users=userService.selectUser();
        return  users;
    }
    
    @RequestMapping("/index.do")
    public String selectStrings(){
        return  "index";
    }
}
LoginController
技术分享图片
package com.zhouwuji.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zhouwuji.service.UserService;

@Controller
public class PIOController {
    
    @Resource
    private UserService userService;
    /**
     *  批量导入表单数据
     * @param myFile
     * @return
     */
       @RequestMapping(value="/importExcel",method=RequestMethod.POST)
       @ResponseBody
       public String importExcel(@RequestParam("uploadfile")CommonsMultipartFile file) {
            ModelAndView modelAndView = new ModelAndView();
            try {
                Integer num = userService.importExcel(file);
                System.out.println(num);
            } catch (Exception e) {
                return "数据导入失败";
            }
            return "数据导入成功";
        }
        
        @RequestMapping(value="/exportExcel",method=RequestMethod.GET)
        public void exportExcel(HttpServletResponse response) {    
            try {
                userService.exportExcel(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    
    
}
PIOController
技术分享图片
package com.zhouwuji.dao;

import java.util.List;

import com.zhouwuji.pojo.User;



public interface UserDao {
     List<User> selectUser(); 
     int   insert(User user);
     
}
UserDao
技术分享图片
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhouwuji.dao.UserDao">
    <select id="selectUser" resultType="com.zhouwuji.pojo.User">
        select * from user
    </select>
    
    <insert id="insert" parameterType="com.zhouwuji.pojo.User" useGeneratedKeys="true">
        insert into user(name,pwd) values(#{name},#{pwd})
    </insert>
    
    <delete id="remove">
        deletes from user where id=#{id}
    </delete>
</mapper>
user.mapper.xml
技术分享图片
package com.zhouwuji.pojo;
/** 
 * Title: MyDemo<br> 
 * Description: <br> 
 * Copyright: Copyright (c) 2018 <br> 
 * Create DateTime: 2018骞?鏈?4鏃?涓嬪崍4:30:32 <br>
 * @author lvlin
 */

public class Student {
private String id;
private String name;
private String sex;
private int age;
private String address;
private String tel;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getSex() {
    return sex;
}
public void setSex(String sex) {
    this.sex = sex;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getTel() {
    return tel;
}
public void setTel(String tel) {
    this.tel = tel;
}
@Override
public String toString() {
    return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", address=" + address + ", tel="
            + tel + "]";
}


}
Student
技术分享图片
package com.zhouwuji.pojo;

public class User   {
    private Integer id;
    private String name;
    private String pwd;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public User(String name,Integer id,  String pwd) {
        super();
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    public User(String name, String pwd) {
        super();
        this.name = name;
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
    }
    public User() {
        super();
    }
    

}
User
技术分享图片
package com.zhouwuji.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.zhouwuji.pojo.User;


public interface UserService {
    List<User> selectUser();
    int    insert(User user);
    int    importExcel(MultipartFile myFile) throws Exception;
    void   exportExcel(HttpServletResponse response) throws IOException;
}
UserService
技术分享图片
package com.zhouwuji.service;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhouwuji.dao.UserDao;
import com.zhouwuji.pojo.User;


/** 
* Title: QuartzService<br> 
* @author Tubu.Zhang
* @Description: 定时器执行调度服务类<br>  
* @version: 1.0
* @Copyright: Copyright (c) 2018 <br> 
* @Create DateTime: Jan 18, 2018 4:17:24 PM <br>
*/
@Service
public class QuartzService {

    @Resource
    private UserDao userDao;
    /**
    * Title: sendInfoToYxtByQuartz<br> 
    * @author 
    * @Description: 调度执行向云学堂发??信息<br> 

    */
    public void sendInfoToYxtByQuartz(){
        
        System.out.println("调度一");
    };
    
    /**
    * Title: deleteLogFileByQuartz<br> 
    * @author Tubu.Zhang
    * @Description: 调度执行删除本地APP下log文件<br> 
    * @param: 
    * @return: 
    * @version: 1.0
    * @Copyright: Copyright (c) 2018 <br> 
    * @Create DateTime: Jan 18, 2018 4:16:45 PM <br>
    */
    public void deleteLogFileByQuartz(){
        
        System.out.println("任务调度二");
        
    };
    
}
QuartzService
技术分享图片
package com.zhouwuji.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.zhouwuji.dao.UserDao;
import com.zhouwuji.pojo.User;
import com.zhouwuji.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";
    
    @Resource
    private UserDao userDao;

    public List<User> selectUser() {
        return userDao.selectUser();
    }

    public int insert(User user) {
        return userDao.insert(user);
    }

    public int importExcel(MultipartFile myFile) throws Exception {
        //        4、对Cell对象读写。
        //获得文件名  
        Workbook workbook = null ;
        String fileName = myFile.getOriginalFilename(); 
        if(fileName.endsWith(XLS)){  
            //  1、用HSSFWorkbook打开或者创建“Excel文件对象”
            workbook = new HSSFWorkbook(myFile.getInputStream());  
        }else if(fileName.endsWith(XLSX)){  
            //2007  
            workbook = new XSSFWorkbook(myFile.getInputStream());  
        }else{
            throw new Exception("文件不是Excel文件");
        }
        //2、用HSSFWorkbook对象返回或者创建Sheet对象
        Sheet sheet = workbook.getSheet("Sheet1");
        int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
        if(rows==0){
            throw new Exception("请填写数据");
        }
        for (int i = 1; i <= rows+1; i++) {
            // 读取左上端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // **读取cell**
               User user = new User();
                 //用户id
                 //3、用Sheet对象返回行对象,用行对象得到Cell对象
                String id = getCellValue(row.getCell(0));
               // user.setId(Integer.valueOf(id));
                //名称
                String name = getCellValue(row.getCell(1));
                user.setName(name);
                //用户密码
                String pwd = getCellValue(row.getCell(2));
                if (!StringUtils.isEmpty(pwd)) {
                    Integer score = Integer.parseInt(pwd);
                    user.setPwd(pwd);
                }
                /*//考试时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
                String dateString = getCellValue(row.getCell(3));  
                if (!StringUtils.isEmpty(dateString)) {
                    Date date=(Date) sdf.parse(dateString);  
                    student.setTime(date);
                }*/
               insert(user);
            }
        }
        
        return  rows-1;
    }
     /**
     * 获得Cell内容
     * 
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                value = cell.getNumericCellValue() + "";
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    Date date = (Date) cell.getDateCellValue();
                    if (date != null) {
                        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                    } else {
                        value = "";
                    }
                } else {
                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                }
                break;
            case HSSFCell.CELL_TYPE_STRING: // 字符串
                value = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                value = cell.getBooleanCellValue() + "";
                break;
            case HSSFCell.CELL_TYPE_FORMULA: // 公式
                value = cell.getCellFormula() + "";
                break;
            case HSSFCell.CELL_TYPE_BLANK: // 空值
                value = "";
                break;
            case HSSFCell.CELL_TYPE_ERROR: // 故障
                value = "非法字符";
                break;
            default:
                value = "未知类型";
                break;
            }
        }
        return value.trim();
    }
    
    public void exportExcel(HttpServletResponse response) throws IOException {
         // 第一步,创建一个webbook,对应一个Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();  
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet("Sheet1");  
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
        HSSFRow row = sheet.createRow(0);  
        // 第四步,创建单元格,并设置值表头 设置表头居中  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  

        HSSFCell cell = row.createCell(0);
        cell.setCellValue("id");  
        cell.setCellStyle(style);  
        cell = row.createCell(1);  
        cell.setCellValue("name");  
        cell.setCellStyle(style);  
        cell = row.createCell(2);  
        cell.setCellValue("pwd");  
        cell.setCellStyle(style);  
       /* cell = row.createCell(3);  
        cell.setCellValue("时间");  
        cell.setCellStyle(style);  */

        // 第五步,写入实体数据 实际应用中这些数据从数据库得到,  
        List<User> list = userDao.selectUser();  

        for (int i = 0; i < list.size(); i++){  
            row = sheet.createRow(i + 1);  
            User stu = list.get(i);  
            // 第四步,创建单元格,并设置值  
            row.createCell(0).setCellValue(stu.getId());  
            row.createCell(1).setCellValue(stu.getName());  
            row.createCell(2).setCellValue(stu.getPwd());  
           /* cell = row.createCell(3);  
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getTime()));  */
        }          
        //第六步,输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        long filename = System.currentTimeMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String fileName = df.format(new Date(filename));// new Date()为获取当前系统时间
        response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
        response.setContentType("application/msexcel");        
        wb.write(output);
        output.close();
    }  

    }
UserServiceImpl
技术分享图片
package com.zhouwuji.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;

public class JasperLocalUtils {
     /**
     *   JRXlsxExporter 导出excel表格  不是JRXlsExporter
     * @param jasperPrint
     * @param defaultFilename
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
     public static void exportExcel(List lists,Map<String,Object> params,String defaultFilename, String resoureFilePath,
             HttpServletResponse response) throws IOException, JRException {
         JasperReport report=judgejrxmlAndjasper(resoureFilePath);
         response.setContentType("application/vnd.ms-excel;charset=GBK"); // 设置头文件信息
         String defaultname = null;
         if (defaultFilename.trim() != null && defaultFilename != null) {
             defaultname = defaultFilename + ".xlsx";
         } else {
             defaultname = "export.xlsx";
         }
         String fileName = new String(defaultname.getBytes("gbk"), "utf-8");
         response.setHeader("Content-disposition", "attachment; filename="
                 + fileName);
         
         JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,judgeDataSourceIsNull(lists));

         ServletOutputStream ouputStream = response.getOutputStream();
         JRXlsxExporter   exporter = new JRXlsxExporter();
         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
         exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE); 
         exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE); 
         //设置Excel表格的背景颜色为默认的白色  
         exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);
         exporter.exportReport();
         ouputStream.flush();
         ouputStream.close();
     }
     
     /**
      *  读取文件导出到本地xlsx文件   并且导出多个sheet数据
      * @param lists              包装的数据 
      * @param defaultFilename    输出文件的名字
      * @param resoureFilePath    读取源文件
      * @param params             包装的参数
      * @throws IOException
      * @throws JRException
      */
     public static void exportLocalExcel(List lists,Map<String,Object> params,String resoureFilePath,String filePathPDF) throws IOException, JRException {
         
         JasperReport report =judgejrxmlAndjasper(resoureFilePath);
         ByteArrayOutputStream outPut=new ByteArrayOutputStream();  
         FileOutputStream outputStream=null;  
         try { 
             
             JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,judgeDataSourceIsNull(lists));
             List<JasperPrint> jasperPrints=new ArrayList<JasperPrint>();
             jasperPrints.add(jasperPrint);
             jasperPrints.add(jasperPrint);
             
             JRXlsxExporter   exporter = new JRXlsxExporter();
            // exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrints);  导出一个
            /**
             * sheetNames 为自定义的数组类型,如:String[] sheetNames = {"自定义1","自定义2","自定义3"};如不需要也可以不配置此项。
             *  JRExporterParameter.JASPER_PRINT_LIST,传入一个listJasperPrint的集合,每个JasperPrint即一个Sheet页。
             */
             exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrints);
            
             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outPut);
              //去除两行之前的空白
             exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE); 
             exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE); 
              //设置为true,即可在一个excel中,每个单独的jasper对象放入到一个sheet页中
             exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.TRUE);
              //自定义sheet名称  sheetNames = {"自定义1","自定义2","自定义3"}
             String[] naneString={"sheet1","sheet2"};
             exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, naneString);
             //设置Excel表格的背景颜色为默认的白色  
             exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);
              //自动选择格式
             exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
             exporter.exportReport(); 
             // File file=new File("D:/xp/report.pdf");  
              File file=new File(filePathPDF);  
              outputStream=new FileOutputStream(file);  
              outputStream.write(outPut.toByteArray());  
         } catch (JRException e) {  
             e.printStackTrace();  
         }catch (Exception e) {  
             e.printStackTrace();  
         }finally{  
             try {  
                 outPut.flush();  
                 outPut.close();  
             } catch (Exception e) {  
                 e.printStackTrace();  
             }  
         }  
     }
     
     
     
     
     
     /**
      *  判断集合是否为空,返回JRDataSource
      * @param fieldValues
      * @return
      */
     
     public  static JRDataSource  judgeDataSourceIsNull(List fieldValues ){
         JRDataSource dataSource = null;
            if (fieldValues != null && fieldValues.size() > 0) {
                dataSource = new JRBeanCollectionDataSource(fieldValues);
            } else {
                dataSource = new JREmptyDataSource();
            }
         return dataSource;
     }
     
     
     /**
      *    
      * @param resoureFilePath 判断是jrxml文件还是jasper文件
      * @return
      */
     public static  JasperReport  judgejrxmlAndjasper(String  resoureFilePath){
        
         JasperReport report =null;
         
         try {
            if (resoureFilePath.endsWith(".jrxml")) {
              report = JasperCompileManager.compileReport(resoureFilePath);
              } else if (resoureFilePath.endsWith(".jasper")){
              report =(JasperReport) JRLoader.loadObjectFromFile(resoureFilePath);
              }
        } catch (JRException e) {
            e.printStackTrace();
        }
         return  report;
     }
     
 
     /**  
      *  导出pdf,注意此处中文问题, 这里应该详细说:主要在ireport里变下就行了。看图
      * 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏
      *  设置字体 font name  为宋体
      *  下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
      */
     public static void exportPdf(List lists,Map<String,Object> params,String defaultFilename, String resoureFilePath,
             HttpServletResponse response) throws IOException, JRException {
         
         response.setContentType("application/pdf;charset=UTF-8");
        
         String defaultname = null;
         if (defaultFilename.trim() != null && defaultFilename != null) {
             defaultname = defaultFilename + ".pdf";
         } else {
             defaultname = "export.pdf";
         }
         String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
         response.setHeader("Content-disposition", "attachment; filename="
                 + fileName);
        
         JasperReport report=judgejrxmlAndjasper(resoureFilePath);
         
         JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,judgeDataSourceIsNull(lists));
         ServletOutputStream ouputStream = response.getOutputStream();
         JRPdfExporter pdfExporter = new JRPdfExporter();
         pdfExporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
         pdfExporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, ouputStream);
         pdfExporter.exportReport();
         ouputStream.flush();  
         ouputStream.close();  
     }
     
     
      /**
       *   读取文件并打印出pdf文件到本地
       * @param lists   
       * @param params
       * @param resoureFilePath 读取文件的地址
       * @param filePathPDF     生成文件的地址
       */
     public static void  exportLocalPDF(List lists,Map<String,Object> params,String resoureFilePath,String filePathPDF){
         JasperReport report =judgejrxmlAndjasper(resoureFilePath);
         ByteArrayOutputStream outPut=new ByteArrayOutputStream();  
         FileOutputStream outputStream=null;  
         try { 
             
             JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,judgeDataSourceIsNull(lists));
             
             JRAbstractExporter exporter=new JRPdfExporter();  
             //创建jasperPrint  
             exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
             //生成输出流  
             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outPut);  
             //屏蔽copy功能  
             exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED,Boolean.TRUE);  
             //加密  
             exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY,Boolean.TRUE);  
              exporter.exportReport();  
             // File file=new File("D:/xp/report.pdf");  
               File file=new File(filePathPDF);  
              outputStream=new FileOutputStream(file);  
              outputStream.write(outPut.toByteArray());  
         } catch (JRException e) {  
             e.printStackTrace();  
         }catch (Exception e) {  
             e.printStackTrace();  
         }finally{  
             try {  
                 outPut.flush();  
                 outPut.close();  
             } catch (Exception e) {  
                 e.printStackTrace();  
             }  
         }  
     }
 
  
}
JasperLocalUtils
技术分享图片
package com.zhouwuji.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.lang.StringUtils;

@SuppressWarnings("unchecked")
public class JasperUtils {

    public static final String PRINT_TYPE = "print";
    public static final String PDF_TYPE = "pdf";
    public static final String EXCEL_TYPE = "excel";
    public static final String HTML_TYPE = "html";
    public static final String WORD_TYPE = "word";

    /**
     * 如果导出的是excel,则需要去掉周围的margin
     * 
     * @param jasperReport
     * @param type
     */
    public static void prepareReport(JasperReport jasperReport, String type) {
        if ("excel".equals(type))
            try {
                Field margin = JRBaseReport.class
                        .getDeclaredField("leftMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("topMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("bottomMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                Field pageHeight = JRBaseReport.class
                        .getDeclaredField("pageHeight");
                pageHeight.setAccessible(true);
                pageHeight.setInt(jasperReport, 2147483647);
            } catch (Exception exception) {

            }

    }

    /**
     * 导出Excel
     * 
     * @param jasperPrint
     * @param defaultFilename
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportExcel(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("application/vnd.ms-excel"); // 设置头文件信息
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".xlsx";
        } else {
            defaultname = "export.xlsx";
        }
        String fileName = new String(defaultname.getBytes("gbk"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        JRXlsxExporter   exporter = new JRXlsxExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE); 
        exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE); 
        //设置Excel表格的背景颜色为默认的白色  
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出pdf,注意此处中文问题, 这里应该详细说:主要在ireport里变下就行了。看图
     * 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
     * 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
     */
    private static void exportPdf(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("application/pdf");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".pdf";
        } else {
            defaultname = "export.pdf";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出html
     * 
     * @param pageIndexStr
     */

    private static void exportHtml(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response, String pageIndexStr)
            throws IOException, JRException {
        response.setContentType("text/html");
        ServletOutputStream ouputStream = response.getOutputStream();
        JRHtmlExporter exporter = new JRHtmlExporter();
        Integer pageIndex = getPageIndex(jasperPrint, request, pageIndexStr); // 得到当前页码
        if (pageIndex != null) { // 如果页码不为空 则设置分页页码
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, pageIndex);
        }
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
                Boolean.FALSE);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();

    }

   
    /**
     * 导出word
     */

    private static void exportWord(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws JRException, IOException {
        response.setContentType("application/msword;charset=utf-8");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".doc";
        } else {
            defaultname = "export.doc";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JRExporter exporter = new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response
                .getOutputStream());
        exporter.exportReport();
    }
    /**
     * description:通过传进来的pageIndexStr 得到当前页码 Date 2013-1-18 上午10:49:38
     * 
     * @param @param jasperPrint
     * @param @param request
     * @param @param pageIndexStr
     * @param @return
     * @return Integer
     */
    private static Integer getPageIndex(JasperPrint jasperPrint,
            HttpServletRequest request, String pageIndexStr) {
        if (pageIndexStr == null || StringUtils.isBlank(pageIndexStr)) { // 如果pageIndexStr为空或空字符串则返回null
            return null;
        }
        Integer pageIndex = 0;
        int lastPageIndex = 0;
        if (jasperPrint.getPages() != null) { // 得到最后一页的 页码
            lastPageIndex = jasperPrint.getPages().size() - 1;
        }
        if ("lastPage".equals(pageIndexStr)) { // 如果字符串==lastPage
            // 则反lastPageIndex的值赋给pageIndex
            // 并返回pageIndex
            pageIndex = lastPageIndex;
            return pageIndex;
        }
        try {
            pageIndex = Integer.parseInt(pageIndexStr);
            if (pageIndex > 0) { // 从ireport
                // 传来的PageIndex是从1开始,而JRExporterParameter.PAGE_INDEX是从0开始的
                pageIndex = pageIndex - 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (pageIndex < 0) {
            pageIndex = 0;
        }
        if (pageIndex > lastPageIndex) {
            pageIndex = lastPageIndex;
        }
        return pageIndex;
    }


    /**
     * 导出入口 (分页显示 导出传入的pageIndex 页的数据)
     * 
     * @param exportType
     *            导出文件的类型
     * @param jaspername
     *            jasper文件的名字 如: xx.jasper
     * @param lists
     *            导出的数据
     * @param request
     * @param response
     * @param defaultFilename默认的导出文件的名称
     * @param pageIndex
     *            需要导出数据的页码 当pageIndex = null时导出所有数据
     */

    @SuppressWarnings("deprecation")
    public static void exportmain(String exportType, String jaspername, Map<String,Object> params,
            List lists, String defaultFilename, String pageIndexStr,HttpServletRequest request,HttpServletResponse response) {
       
        String filenurl = request.getServletContext().getRealPath("jasper/"+ jaspername);
        File file = new File(filenurl);
        InputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        export(lists, exportType,params, defaultFilename, is, request, response,
                pageIndexStr);
    }

    /**
     * 按照类型导出不同格式文件
     * 
     * @param datas
     *            数据
     * @param type
     *            文件类型
     * @param is
     *            jasper文件的来源
     * @param request
     * @param response
     * @param defaultFilename默认的导出文件的名称
     */

    private static void export(Collection datas, String type,Map<String,Object> params,
            String defaultFilename, InputStream is, HttpServletRequest request,
            HttpServletResponse response, String pageIndexStr) {
        try {
            
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
            
            prepareReport(jasperReport, type);
            
            JRDataSource ds = new JRBeanCollectionDataSource(datas, false);
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, params, ds);
            if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint, defaultFilename, request, response);
            } else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, defaultFilename, request, response);
            } else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, defaultFilename, request, response,
                        pageIndexStr);
            } else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, defaultFilename, request, response);
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
   
    
    
    

}
JasperUtils
技术分享图片
package com.zhouwuji.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.PDFOperator;
import org.apache.pdfbox.util.PDFTextStripper;

public class PDFboxUtil {
    
    //创建pdf 文件
     public static void createHelloPDF() {
                 
                 PDDocument doc = null;
                 PDPage page = null;
         
                 try {
                     doc = new PDDocument();
                     page = new PDPage();
                     doc.addPage(page);
                     PDFont font = PDType1Font.HELVETICA_BOLD;
                     PDPageContentStream content = new PDPageContentStream(doc, page);
                     content.beginText();
                     content.setFont(font, 12);
                     content.moveTextPositionByAmount(100, 700);
                     content.drawString("hello");
         
                     content.endText();
                     content.close();
                     doc.save("D:/xp/pdfwithText.pdf");
                     doc.close();
                 } catch (Exception e) {
                     System.out.println(e);
                 }
             }
     
     //读取pdf文件
     public static void readPDF() {
                 PDDocument helloDocument = null;
                 try {
                     helloDocument = PDDocument.load(new File(
                             "D:/xp/test.pdf"));
                     PDFTextStripper textStripper = new PDFTextStripper("GBK");
                     System.out.println(textStripper.getText(helloDocument));
                     helloDocument.close();
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
     //修改pdf
     public static void doIt( String inputFile, String outputFile, String strToFind, String message)
       throws IOException, COSVisitorException
         {
       // the document
       PDDocument doc = null;
       try
       {
           doc = PDDocument.load(inputFile);
           PDFTextStripper stripper=new PDFTextStripper("ISO-8859-1");
           List pages = doc.getDocumentCatalog().getAllPages();
           for( int i=0; i<pages.size(); i++ )
           {
               PDPage page = (PDPage)pages.get( i );
               PDStream contents = page.getContents();
               PDFStreamParser parser = new PDFStreamParser(contents.getStream() );
               parser.parse();
               List tokens = parser.getTokens();
               for( int j=0; j<tokens.size(); j++ )
               {
                   Object next = tokens.get( j );
                   if( next instanceof PDFOperator )
                   {
                       PDFOperator op = (PDFOperator)next;
                       //Tj and TJ are the two operators that display
                       //strings in a PDF
                       if( op.getOperation().equals( "Tj" ) )
                       {
                           //Tj takes one operator and that is the string
                           //to display so lets update that operator
                           COSString previous = (COSString)tokens.get( j-1 );
                           String string = previous.getString();
                           string = string.replaceFirst( strToFind, message );
                           System.out.println(string);
                           System.out.println(string.getBytes("GBK"));
                           previous.reset();
                           previous.append( string.getBytes("GBK") );
                       }
                       else if( op.getOperation().equals( "TJ" ) )
                       {
                           COSArray previous = (COSArray)tokens.get( j-1 );
                           for( int k=0; k<previous.size(); k++ )
                           {
                               Object arrElement = previous.getObject( k );
                               if( arrElement instanceof COSString )
                               {
                                   COSString cosString = (COSString)arrElement;
                                   String string = cosString.getString();
                                   string = string.replaceFirst( strToFind, message );
                                   cosString.reset();
                                   cosString.append( string.getBytes("GBK") );
                               }
                           }
                       }
                   }
               }
               //now that the tokens are updated we will replace the
               //page content stream.
               PDStream updatedStream = new PDStream(doc);
               OutputStream out = updatedStream.createOutputStream();
               ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
               tokenWriter.writeTokens( tokens );
               page.setContents( updatedStream );
           }
           doc.save( outputFile );
       }
       finally
       {
           if( doc != null )
           {
               doc.close();
           }
       }
   }
      //pdf转成图片
     public static void toImage() {
            try {
                PDDocument doc = PDDocument
                        .load("D:/xp/pdfwithText.pdf");
                int pageCount = doc.getPageCount();
                System.out.println(pageCount);
                List pages = doc.getDocumentCatalog().getAllPages();
                for (int i = 0; i < pages.size(); i++) {
                    PDPage page = (PDPage) pages.get(i);
                    BufferedImage image = page.convertToImage();
                    Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
                    ImageWriter writer = (ImageWriter) iter.next();
                    File outFile = new File("D:/xp/pdf.jpg");
                    FileOutputStream out = new FileOutputStream(outFile);
                    ImageOutputStream outImage = ImageIO
                            .createImageOutputStream(out);
                    writer.setOutput(outImage);
                    writer.write(new IIOImage(image, null, null));
                }
                doc.close();
                System.out.println("over");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }     
     
     
     
     
     
     
}
PDFboxUtil
技术分享图片
package com.zhouwuji.util;
import java.util.Random;
import java.util.UUID;

/**
 * Title: MyDemo<br>
 * Description: <br>
 * Copyright: Copyright (c) 2018 <br>
 * Create DateTime: 2018年1月14日 下午3:44:07 <br>
 * @author lvlin
 */

public class RandomParam {
    static Random r = new Random();

    public static String getId() {
        return UUID.randomUUID().toString();
    }

   /*public static String getName() {
        // String[] n1={"赵","钱","孙","李","周","吴","郑","王","冯","陈","诸","魏"};
        // String[]
        // n2={"一","二","三","四","五","六","七","八","九","十","十一","十二","十三","十四"};
        String[] n1 = { "张", "王" };
        String[] n2 = { "一", "二" };
        return n1[r.nextInt(n1.length)] + n2[r.nextInt(n2.length)];
    }

    public static String getSex() {
        String[] sex = { "男", "女" };
        return sex[r.nextInt(2)];
    }

    public static int getAge() {
        return r.nextInt(15) + 18;
    }

    public static String getTel() {
        String[] tel = { "133", "136", "138", "152", "177", "188" };
        return tel[r.nextInt(tel.length)] + "****" + (r.nextInt(10) - 1) + (r.nextInt(10)) + (r.nextInt(10))
                + (r.nextInt(10));
    }

    public static String getAdd() {
        String[] add = { "北京", "河北", "山西", "内蒙", "辽宁", "吉林", "黑龙江", "上海", "江苏" };
        return add[r.nextInt(add.length)];
    }*/
}
RandomParam
技术分享图片
package com.zhouwuji.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisUtil {
        private static final Logger log = Logger.getLogger(RedisUtil.class);
        private static JedisPool jedisPool = null;
        private static ShardedJedisPool shardedJedisPool = null;
        /**
         * 初始化Redis连接池
         */
        static {
            try {
                // 加载redis配置文件
                ResourceBundle bundle = ResourceBundle.getBundle("redis");
                if (bundle == null) {
                    throw new IllegalArgumentException(
                            "[redis.properties] is not found!");
                }
                int maxActivity = Integer.valueOf(bundle
                        .getString("redis.pool.maxActive"));
                int maxIdle = Integer.valueOf(bundle
                        .getString("redis.pool.maxIdle"));
                long maxWait = Long.valueOf(bundle.getString("redis.pool.maxWait"));
                boolean testOnBorrow = Boolean.valueOf(bundle
                        .getString("redis.pool.testOnBorrow"));
                boolean onreturn = Boolean.valueOf(bundle
                        .getString("redis.pool.testOnReturn"));
                // 创建jedis池配置实例
                JedisPoolConfig config = new JedisPoolConfig();
                // 设置池配置项值
                config.setMaxTotal(maxActivity);
                config.setMaxIdle(maxIdle);  //最大空闲连接数
                config.setMaxWaitMillis(maxWait);
                config.setTestOnBorrow(testOnBorrow);
                config.setTestOnReturn(onreturn);
                jedisPool=new JedisPool(config, bundle.getString("redis.ip"), Integer.valueOf(bundle.getString("redis.port")), 200, "123456");
                // slave链接
                List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
                JedisShardInfo shardInfo=new JedisShardInfo(bundle.getString("redis.ip"), Integer
                        .valueOf(bundle.getString("redis.port1")));
                shardInfo.setPassword("123456");
                shards.add(shardInfo);
                shardedJedisPool = new ShardedJedisPool(config, shards);
                log.info("初始化Redis连接池success");
            } catch (Exception e) {
                log.error("初始化Redis连接池 出错!", e);
            }
        }

        /**
         * 获取Jedis实例
         * 
         * @return
         */
        public synchronized static Jedis getJedis() {
            try {
                if (jedisPool != null) {
                    Jedis resource = jedisPool.getResource();
                    return resource;
                } else {
                    return null;
                }
            } catch (Exception e) {
                log.error("Redis缓存获取Jedis实例 出错!", e);
                return null;
            }
        }

        /**
         * 获取shardedJedis实例
         * 
         * @return
         */
        public static ShardedJedis getShardedJedis() {
            try {
                if (shardedJedisPool != null) {
                    ShardedJedis resource = shardedJedisPool.getResource();
                    return resource;
                } else {
                    return null;
                }
            } catch (Exception e) {
                log.error("Redis缓存获取shardedJedis实例 出错!", e);
                return null;
            }
        }

        /**
         * 释放jedis资源
         * 
         * @param jedis
         */
        public static void returnResource(final Jedis jedis) {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 释放shardedJedis资源
         * 
         * @param jedis
         */
        public static void returnResource(final ShardedJedis shardedJedis) {
            if (shardedJedis != null) {
                shardedJedisPool.returnResource(shardedJedis);
            }
        }

        /**
         * 向缓存中设置字符串内容
         * 
         * @param key
         *            key
         * @param value
         *            value
         * @return
         * @throws Exception
         */
        public static boolean set(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                if(jedis != null){
                    jedis.set(key, value);
                }
                return true;
            } catch (Exception e) {
                log.error("Redis缓存设置key值 出错!", e);
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * 判断key是否存在
         */
        public static boolean exists(String key){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis == null) {
                    return false;
                } else {
                    return jedis.exists(key);
                }
            } catch (Exception e) {
                log.error("Redis缓存判断key是否存在 出错!", e);
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * 删除缓存中的对象,根据key
         * @param key
         * @return
         */
        public static boolean del(String key) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.del(key);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        
        //*******************key-value****************start
        
        /**
         * 向缓存中设置对象
         * 
         * @param key
         * @param value
         * @return
         */
        public static boolean set(String key, Object value) {
            Jedis jedis = null;
            try {
                String objectJson = JSONObject.fromObject(value).toString();
                jedis = getJedis();
                if (jedis != null) {
                    jedis.set(key, objectJson);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }

        /**
         * 根据key 获取内容
         * 
         * @param key
         * @return
         */
        public static Object get(String key) {
            ShardedJedis jedis = null;
            try {
                jedis = shardedJedisPool.getResource();
                Object value = jedis.get(key);
                return value;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                shardedJedisPool.returnResource(jedis);
            }
        }
        
        /**
         * 根据key 获取对象
         * 
         * @param key
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T> T get(String key, Class<T> clazz) {
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    return (T) JSONObject.toBean(JSONObject.fromObject(jedis.get(key)), clazz);
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        //*******************key-value****************end
        
        //*************** 操作list****************start
        /**
         * 向缓存中设置对象 
         * @param key
         * @param list
         * T string calss
         * @return
         */
        public static <T> boolean setList(String key,List<T> list){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                if (jedis != null) {
                    for (T vz : list) {
                        if (vz instanceof String) {
                            jedis.lpush(key, (String) vz);
                        } else {
                            String objectJson = JSONObject.fromObject(vz).toString();
                            jedis.lpush(key, objectJson);
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        
        @SuppressWarnings("unchecked")
        public static <T> List<T> getListEntity(String key,Class<T> entityClass){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    List<String> valueJson = jedis.lrange(key, 0, -1);
                    JSONArray json = new JSONArray();
                    json.addAll(valueJson);
                    JSONArray jsonArray = JSONArray.fromObject(json.toString());
                    return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        public static List<String> getListString(String key){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    return jedis.lrange(key, 0, -1);
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        //*************** 操作list****************end
        
        //*************** 操作map****************start
        public static <K,V> boolean setMap(String key,Map<String,V> map){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                if (jedis != null) {
                    Set<Map.Entry<String, V>> entry = map.entrySet();
                    for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
                        Map.Entry<String, V> kv = ite.next();
                        if (kv.getValue() instanceof String) {
                            jedis.hset(key, kv.getKey(), (String) kv.getValue());
                        }else if (kv.getValue() instanceof List) {
                            jedis.hset(key, kv.getKey(), JSONArray.fromObject(kv.getValue()).toString());
                        } else {
                            jedis.hset(key, kv.getKey(), JSONObject.fromObject(kv.getValue()).toString());
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        public static boolean setMapKey(String key,String mapKey,Object value){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                if (jedis != null) {
                    if (value instanceof String) {
                        jedis.hset(key, mapKey, String.valueOf(value));
                    } else if (value instanceof List) {
                        jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
                    } else {
                        jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
                    }
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * seconds key和value 保存的有效时间(单位:秒)
         * @return
         */
        public static boolean setMapKeyExpire(String key,String mapKey,Object value, int seconds){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                if (jedis != null) {
                    if (value instanceof String) {
                        jedis.hset(key, mapKey, String.valueOf(value));
                    } else if (value instanceof List) {
                        jedis.hset(key, mapKey, JSONArray.fromObject(value).toString());
                    } else {
                        jedis.hset(key, mapKey, JSONObject.fromObject(value).toString());
                    }
                    jedis.expire(key, seconds);
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        @SuppressWarnings("unchecked")
        public static <K,V> Map<String,V> getMap(String key){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
                    return map;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        @SuppressWarnings("unchecked")
        public static <K,V> Map<String,V> getMapEntityClass(String key,Class<V> clazz){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
                    Set<Map.Entry<String, V>> entry = map.entrySet();
                    for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
                        Map.Entry<String, V> kv = ite.next();
                        map.put(kv.getKey(), (V) JSONObject.toBean(JSONObject.fromObject(kv.getValue()), clazz));
                    }
                    return map;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        @SuppressWarnings("unchecked")
        public static <K,V> Map<String,List<V>> getMapList(String key,Class<V> clazz){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    Map<String, V> map = (Map<String, V>) jedis.hgetAll(key);
                    Set<Map.Entry<String, V>> entry = map.entrySet();
                    for (Iterator<Map.Entry<String, V>> ite = entry.iterator(); ite.hasNext();) {
                        Map.Entry<String, V> kv = ite.next();
                        JSONArray jsonArray = JSONArray.fromObject(kv.getValue());
                        map.put(kv.getKey(), (V) JSONArray.toCollection(jsonArray, clazz));
                    }
                    return (Map<String, List<V>>) map;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        @SuppressWarnings("unchecked")
        public static <T> List<T> getMapKeyListEntity(String key,String mapKey,
                Class<T> entityClass){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if (jedis != null) {
                    String valueJson = jedis.hget(key, mapKey);
                    JSONArray jsonArray = JSONArray.fromObject(valueJson);
                    return (List<T>) JSONArray.toCollection(jsonArray, entityClass);
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        @SuppressWarnings("unchecked")
        public static <T> T getMapKeyEntity(String key,String mapKey,
                Class<T> entityClass){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if(jedis != null){
                String valueJson=jedis.hget(key, mapKey);
                return (T) JSONObject.toBean(JSONObject.fromObject(valueJson), entityClass);
                }else{return null;}
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        public static Object getMapKey(String key,String mapKey){
            ShardedJedis jedis = null;
            try {
                jedis = getShardedJedis();
                if(jedis != null){
                return jedis.hget(key, mapKey);
                }else{return null;}
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        public static boolean delMapKey(String key,String mapKey){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.hdel(key, mapKey);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        public static boolean hexists(String key,String mapKey){
            ShardedJedis jedis = null;
            try {
                jedis = shardedJedisPool.getResource();
                return jedis.hexists(key,mapKey);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                shardedJedisPool.returnResource(jedis);
            }
        }
        //*************** 操作map****************end
        
        //***************计数器应用INCR,DECR****************begin
        //Redis的命令都是原子性的,你可以轻松地利用INCR,DECR命令来构建计数器系统
        
        /**
         * incr(key):名称为key的string增1操作
         */
        public static boolean incr(String key){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.incr(key);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * incrby(key, integer):名称为key的string增加integer
         */
        public static boolean incrBy(String key, int value){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.incrBy(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * decr(key):名称为key的string减1操作
         */
        public static boolean decr(String key){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.decr(key);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * decrby(key, integer):名称为key的string减少integer
         */
        public static boolean decrBy(String key, int value){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.decrBy(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        //***************计数器应用INCR,DECR****************end
        
        //***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************begin
        /**
         * 向名称为key的zset中添加元素member,score用于排序。
         * 如果该元素已经存在,则根据score更新该元素的顺序
         */
        public static boolean zadd(String key, double score, String member){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.zadd(key, score, member);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * 删除名称为key的zset中的元素member
         */
        public static boolean zrem(String key, String... members){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.zrem(key, members);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * 返回集合中score在给定区间的元素
         */
        public static Set<String> zrangeByScore(String key, double min, double max){
            ShardedJedis jedis = null;
            try {
                jedis = shardedJedisPool.getResource();
                return jedis.zrangeByScore(key, min, max);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        //***************使用sorted set(zset)甚至可以构建有优先级的队列系统***************end
        
        //***************sorted set 处理***************************************begin
        //zset 处理
        public static boolean zaddObject(String key, double score, Object value){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                String objectJson = JSONObject.fromObject(value).toString();
                jedis.zadd(key, score, objectJson);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * score值递减(从大到小)次序排列。
         * @param key
         * @param max score
         * @param min score
         * @param entityClass
         * @return
         */
        @SuppressWarnings("unchecked")
        public static  <T> List<T> zrevrangeByScore(String key,double max,double min, 
                Class<T> entityClass){
            ShardedJedis jedis = null;
            try {
                jedis =shardedJedisPool.getResource();
                Set<String> set=jedis.zrevrangeByScore(key, max, min);
                List<T> list=new ArrayList<T>();
                for (String str : set) {  
                    list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
                } 
                return list;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        /**
         * score值递减(从大到小)次序排列。
         * @param key
         * @param max score
         * @param min score
         * @param offset count (类似mysql的 LIMIT)
         * @param entityClass
         * @return
         */
        @SuppressWarnings("unchecked")
        public static  <T> List<T> zrevrangeByScore(String key,double max,double min,
                int offset, int count,Class<T> entityClass){
            ShardedJedis jedis = null;
            try {
                jedis =shardedJedisPool.getResource();
                Set<String> set=jedis.zrevrangeByScore(key, max, min,offset,count);
                List<T> list=new ArrayList<T>();
                for (String str : set) {  
                    list.add((T) JSONObject.toBean(JSONObject.fromObject(str), entityClass));
                } 
                return list;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                returnResource(jedis);
            }
        }
        
        
        //得到总记录数
        public static long zcard(String key){
            ShardedJedis jedis = null;
            try {
                jedis =shardedJedisPool.getResource();
                return jedis.zcard(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            } finally {
                returnResource(jedis);
            }
        }
        
        //删除 元素
        public static  boolean zremObject(String key, Object value){
            Jedis jedis = null;
            try {
                jedis = getJedis();
                String objectJson = JSONObject.fromObject(value).toString();
                jedis.zrem(key, objectJson);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }
        
        //统计zset集合中score某个范围内(1-5),元素的个数
        public static long zcount(String key,double min, double max){
            ShardedJedis jedis = null;
            try {
                jedis =shardedJedisPool.getResource();
                return jedis.zcount(key,min,max);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            } finally {
                returnResource(jedis);
            }
        }
        
        //查看zset集合中元素的score
        public static double zscore(String key,Object value){
            ShardedJedis jedis = null;
            try {
                jedis =shardedJedisPool.getResource();
                String objectJson = JSONObject.fromObject(value).toString();
                return jedis.zscore(key,objectJson);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            } finally {
                returnResource(jedis);
            }
        }
        //**************sorted set******************************************end
        
        //***********************Redis Set集合操作**************************begin
        /**
         * sadd:向名称为Key的set中添加元素,同一集合中不能出现相同的元素值。(用法:sadd set集合名称 元素值)
         * @param key
         * @param value
         * @return
         */
        public static boolean sadd(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.sadd(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }

        /**
         * srem:删除名称为key的set中的元素。(用法:srem set集合名称 要删除的元素值)
         * 
         * @param key
         * @param value
         * @return
         */
        public static boolean srem(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.srem(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }

        /**
         * sdiff:返回所有给定key与第一个key的差集。(用法:sdiff set集合1 set集合2)
         * 
         * @param key1
         * @param key2
         * @return
         */
        public static Set<String> sdiff(String key1, String key2) {
            Jedis jedis = null;
            Set<String> diffList = null;
            try {
                jedis = getJedis();
                diffList = jedis.sdiff(key1, key2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                returnResource(jedis);
            }
            return diffList;
        }

        /**
         * sismember:判断某个值是否是集合的元素。(用法:sismember 集合1 指定的元素值)
         * 
         * @param key
         * @param value
         * @return
         */
        public static boolean sismember(String key, String value) {
            ShardedJedis jedis = null;
            try {
                jedis = shardedJedisPool.getResource();
                return jedis.sismember(key, value);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                returnResource(jedis);
            }
        }

        /**
         * smembers(key) :返回名称为key的set的所有元素
         * 
         * @param key
         * @return
         */
        public static Set<String> smembers(String key) {
            Jedis jedis = null;
            Set<String> list = null;
            try {
                jedis = getJedis();
                list = jedis.smembers(key);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                returnResource(jedis);
            }
            return list;
        }
        
        //***********************Redis Set集合操作****************************end
}
RedisUtil
技术分享图片
package com.zhouwuji.util;
import redis.clients.jedis.Jedis;  
import redis.clients.jedis.JedisPool;  
import redis.clients.jedis.JedisPoolConfig; 
public class RedisUtils {
     //Redis服务器IP  
    private static String ADDR = "100.105.7.167";  
     //Redis的端口号  
    private static int PORT = 6379;  
    //可用连接实例的最大数目,默认值为8;  
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。  
    private static int MAX_ACTIVE = 24;  
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。  
    private static int MAX_IDLE = 2;  
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;  
    private static int MAX_WAIT = 10;  
          
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;  
    private static boolean TEST_ON_BORROW = true;  
    private static JedisPool jedisPool = null;  
    /** 
     * 初始化Redis连接池 
     */  
     static {  
         try {  
              JedisPoolConfig config = new JedisPoolConfig();  
              config.setMaxTotal(MAX_ACTIVE);  
              config.setMaxIdle(MAX_IDLE);  
              config.setMaxWaitMillis(MAX_WAIT);  
              config.setTestOnBorrow(TEST_ON_BORROW); 
              jedisPool=new JedisPool(config, ADDR, PORT, 200, "123456");
         } catch (Exception e) {  
              e.printStackTrace();  
         }  
     }  
       
     /** 
      * 获取Jedis实例 
      * @return 
      */  
     public synchronized static Jedis getJedis() {  
         try {  
             if (jedisPool != null) {  
                 Jedis resource = jedisPool.getResource();  
                 return resource;  
             } else {  
                 return null;  
             }  
         } catch (Exception e) {  
             e.printStackTrace();  
             return null;  
         }  
     }  
            
     /** 
      * 释放jedis资源 
      * @param jedis 
      */  
      public static void returnResource(final Jedis jedis) {  
          if (jedis != null) {  
               jedisPool.returnResourceObject(jedis);  
          }  
      }  
}
RedisUtils
技术分享图片
package com.zhouwuji.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.xmlbeans.impl.xb.xsdschema.Public;

import com.bea.xml.stream.StaticAllocator;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.Transaction;

public class RedisTest {
    /**
     * 通俗点讲,watch 命令就是标记一个键,如果标记一个键
     * 在提交事务前如果该键被别人修改过,拿实物就会失败,这种情况通常可以在程序中
     * 重新在尝试一次
     * 首先标记了键balance, 然后检查余额是否足够,不足就取消标记,并不做扣减;
     * 足够的话,就启动事务进行更新操作
     * 如果在此期间balance 被其他人修改,那在提交事务,执行(exec)时就会报错
     * 程序中通常可以捕获这类错误在重新执行一次,直到成功 
     * @param args
     */
    public static void main(String[] args) {
        Jedis jedis = RedisUtils.getJedis();
         Transaction transaction= jedis.multi();
         transaction.set("k11", "v11");
         transaction.exec();
        
        System.out.println(jedis.get("k11")); 
        
    }
    public boolean transaction(){
        Jedis jedis = RedisUtils.getJedis();
        int balance;//可用余额
        int debt;//前额
        int amtToSubtract=10;//实刷金额
        jedis.watch("balance");
        //jedis.set("balance", "5");//
        balance=Integer.parseInt(jedis.get("balance"));
        if (balance<amtToSubtract) {
            jedis.unwatch();
            System.out.println("modify");
            return false;
        } else {
           System.out.println("transaction");
            Transaction transaction=jedis.multi();
            transaction.decrBy("balance",amtToSubtract);
            transaction.incrBy("DEBT", amtToSubtract);
            transaction.exec();
            balance=Integer.parseInt(jedis.get("balance"));
            debt=Integer.parseInt(jedis.get("debt"));
            return true;            
        }
    }
    public static void testRedis() {
        /*
         * Jedis jedis=RedisUtil.getJedis();
         * System.out.println(jedis.keys("*")); String values=
         * RedisUtil.getShardedJedis().get("k1"); System.out.println(values);
         */
        Jedis jedis = RedisUtils.getJedis();
        Set<String> keysSet = jedis.keys("*");
        Iterator<String> vlues = keysSet.iterator();
        for (Iterator iterator = keysSet.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println(string);
        }

        System.out.println(jedis.ttl("k1"));

        System.out.println(jedis.get("k1"));

        jedis.set("k4", "v4");
        System.out.println(jedis.get("k4"));

        jedis.mset("k5", "v5", "k6", "v6");
        System.out.println(jedis.mget("k5", "k6", "k7"));

        // list
        // jedis.lpush("mylist","list1","v1","list2","v2");
        List<String> list = jedis.lrange("mylist", 0, -1);
        for (String string : list) {
            System.out.println("list数据类型" + string);
        }

        // set
        jedis.sadd("set1", "v1");
        jedis.sadd("set1", "v2");
        jedis.sadd("set1", "v3");
        Set<String> set1 = jedis.smembers("set1");
        for (Iterator iterator = set1.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println("set数据类型" + string);
        }

        // hash
        jedis.hset("hash1", "username", "admin");
        jedis.hset("hash1", "password", "123456");
        System.out.println("hash数据类型" + jedis.hget("hash1", "username"));

        Map<String, String> maps = new HashMap<String, String>();
        maps.put("sex", "man");
        maps.put("age", "18");
        jedis.hmset("hash1", maps);
        List<String> result = jedis.hmget("hash1", "sex", "username",
                "password", "age");
        System.out.println(result.size());
        for (String string : result) {
            System.out.println(result);
        }
        // zset
        jedis.zadd("zset1", 62d, "v1");
        jedis.zadd("zset1", 72d, "v2");
        jedis.zadd("zset1", 82d, "v3");
        Set<String> s1 = jedis.zrange("zset1", 0, -1);
        for (Iterator iterator = s1.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println("zset数据" + string);
        }
    }

}
RedisTest
技术分享图片
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/orcl
jdbc.username=root
jdbc.password=123456
jdbc.properties
技术分享图片
<?xml version="1.0" encoding="UTF-8"?>  
  
<!-- 从高到地低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->  
<!-- 日志输出规则  根据当前ROOT 级别,日志输出时,级别高于root默认的级别时  会输出 -->  
<!-- 以下  每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志-->  
  
  
<!-- 属性描述 scan:性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,
默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。   
    debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->  
<configuration scan="true" scanPeriod="60 seconds" debug="false">  
    <!-- 定义日志文件 输入位置 -->  
    <property name="log_dir" value="/logs" />  
    <!-- 日志最大的历史 30天 -->  
    <property name="maxHistory" value="30"/>  
    <!-- ConsoleAppender 控制台输出日志 -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <!-- 对日志进行格式化 -->  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger -%msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
    <!-- ERROR级别日志 -->  
    <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender-->  
    <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- 过滤器,只记录WARN级别的日志 -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>ERROR</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!--日志输出位置  可相对、和绝对路径 -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/error-log.log</fileNamePattern>  
            <!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件假设设置每个月滚动,且<maxHistory>是6,  
            则只保存最近6个月的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除-->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
          
        <!-- 按照固定窗口模式生成日志文件,当文件大于20MB时,生成新的日志文件。窗口大小是1到3,当保存了3个归档文件后,将覆盖最早的日志。   
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">     
          <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/.log.zip</fileNamePattern>     
          <minIndex>1</minIndex>     
          <maxIndex>3</maxIndex>     
        </rollingPolicy>   -->  
        <!-- 查看当前活动文件的大小,如果超过指定大小会告知RollingFileAppender 触发当前活动文件滚动   
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">     
            <maxFileSize>5MB</maxFileSize>     
        </triggeringPolicy>   -->  
          
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
    <!-- WARN级别日志 appender -->  
    <appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- 过滤器,只记录WARN级别的日志 -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>WARN</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- 按天回滚 daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/warn-log.log  
            </fileNamePattern>  
            <!-- 日志最大的历史 60天 -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- INFO级别日志 appender -->  
    <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- 过滤器,只记录INFO级别的日志 -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>INFO</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- 按天回滚 daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/info-log.log  
            </fileNamePattern>  
            <!-- 日志最大的历史 60天 -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- DEBUG级别日志 appender -->  
    <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- 过滤器,只记录DEBUG级别的日志 -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>DEBUG</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- 按天回滚 daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/debug-log.log  
            </fileNamePattern>  
            <!-- 日志最大的历史 60天 -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- TRACE级别日志 appender -->  
    <appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- 过滤器,只记录ERROR级别的日志 -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>TRACE</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- 按天回滚 daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/trace-log.log  
            </fileNamePattern>  
            <!-- 日志最大的历史 60天 -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
  
    <logger name="java.sql.PreparedStatement" value="DEBUG" />    
    <logger name="java.sql.Connection" value="DEBUG" />    
    <logger name="java.sql.Statement" value="DEBUG" />    
    <logger name="com.ibatis" value="DEBUG" />    
    <logger name="com.ibatis.common.jdbc.SimpleDataSource" value="DEBUG" />    
    <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG"/>    
    <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" value="DEBUG" />    
      
      
      
    <!-- root级别   DEBUG -->  
    <root level="debug">  
        <!-- 控制台输出 -->  
        <appender-ref ref="STDOUT" />  
        <!-- 文件输出 -->  
        <appender-ref ref="ERROR" />  
        <appender-ref ref="INFO" />  
        <appender-ref ref="WARN" />  
        <appender-ref ref="DEBUG" />  
        <appender-ref ref="TRACE" />  
    </root>  
</configuration>  
logback.xml
技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     
    <!-- 定时上传STFP Server上send文件夹下文件、移动send至bak文件夹下文件和本地APP上logs写入文件 begin -->
    <bean id="sendInfoToYxtJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
        <property name="targetObject">
            <ref bean="quartzService"/>
        </property>
        <property name="targetMethod">
            <value>sendInfoToYxtByQuartz</value>
        </property>
        <property name="concurrent">
            <value>false</value>
        </property>
    </bean>
    
    <bean id="sendInfoToYxtJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean" >
        <property name="jobDetail">
            <ref bean="sendInfoToYxtJobDetail"/>
        </property>
        <property name="cronExpression">
            <!-- 每3秒执行一次 (0/3 * * * * ?) -->
            <!-- 每天20:00执行 (0 0 20 * * ?) -->
            <value>0 0 20 * * ?</value>
        </property>
    </bean>
    <!-- 定时上传STFP Server上send文件夹下文件、移动send至bak文件夹下文件和本地APP上logs写入文件 end -->
        
    <!-- 定时删除本地APP上logs文件夹下文件 begin --> 
    <bean id="deleteLogFilesJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
        <property name="targetObject">
            <ref bean="quartzService"/>
        </property>
        <property name="targetMethod">
            <value>deleteLogFileByQuartz</value>
        </property>
        <property name="concurrent">
            <value>false</value>
        </property>
    </bean>
    
    <bean id="deleteLogFilesJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean" >
        <property name="jobDetail">
            <ref bean="deleteLogFilesJobDetail"/>
        </property>
        <property name="cronExpression">
            <!-- 每3秒执行一次 (0/3 * * * * ?) -->
            <!-- 每天20:05执行 (0 5 20 * * ?) -->
            <value>0 0 20 * * ?</value>
        </property>
    </bean>
    <!-- 定时删除本地APP上logs文件夹下文件 begin -->
    
    <!-- 总管理类 如果将lazy-init=‘false‘那么容器启动就会执行调度程序 -->
    <bean id="startQuertz" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="sendInfoToYxtJobTrigger"/>
                <ref bean="deleteLogFilesJobTrigger"/>
            </list>
        </property>
    </bean>
</beans>
quartzu.xml
技术分享图片
#最大连接数
redis.pool.maxActive=100
#最大空闲数
redis.pool.maxIdle=20
#获取连接时的最大等待毫秒数(如果设置为阻塞是BlockExhausted),如果超时就抛异常,小于零,阻塞不确定的时间默认-1 。
redis.pool.maxWait=3000
#最小空闲连接数
redis.pool.minIdle=0
#在获取连接的时候检查有效性,默认false
redis.pool.testOnBorrow=false
#
redis.pool.testOnReturn=false


redis.ip=100.105.7.167
#redis.ip=127.0.0.1
redis.port=6379
redis.port1=6379
redis.password=123456
redis.properties
技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-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/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
   <bean id="stringConverter"
        class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
    <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean> 
   
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    
    <!-- 声明式事务配置 开始 -->
    <!-- 配置事务管理器 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
     <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
        <!--     配置哪些方法使用什么样的事务,配置事务的传播特性 -->
            <tx:method name="add" propagation="REQUIRED" />
            <tx:method name="insert" propagation="REQUIRED" />
            <tx:method name="update" propagation="REQUIRED" />
            <tx:method name="delete" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="get" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution(* com.zhouwuji.service.impl.*.*(..))"
            id="pointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config> 
    
    <!-- 声明式事务配置 结束 -->
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/zhouwuji/dao/*.mapper.xml"></property>
    </bean>
    
    <context:component-scan base-package="com.zhouwuji" />
    
    <!-- 6.spring和mybaits整合,自动扫映射输入参数 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhouwuji.dao" />
    </bean>
    
      <!-- 定义视图解析器 -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                 <property name="prefix" value="/WEB-INF/view/" />
                <property name="suffix" value=".jsp" />
    </bean> 
    <!-- 静态映射对应的文件 
    <mvc:resources location="js/**" mapping="/WEB-INF/view/js"/>-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <!-- 定时功能清理机制,包含临时文档删除 -->
    <import resource="classpath:quartzu.xml"/>
    
    
    
     <!-- 1.springMVC上传文件时,需要配置CommonsMultipartResolver处理器 -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置默认的编码格式 -->
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxInMemorySize" value="10240" /> <!-- 最大内存大小 (10240) -->
        <!-- 指定所上传文件的总的大小不能超过200kb, 注意maxUploadSize属性点 限制 不是针对单个文件, 而是所有文件的容量总和 -->
        <property name="maxUploadSize" value="-1" /><!-- 最大文件大小,-1为无限止(-1) -->
    </bean>
    <!-- 2.springMVC在超出上传文件限制时,会抛出 org.springframework.web.multipart.MaxUploadSizeExceededException 
        该异常时SpringMVC在检查上传文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
     <bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 在遇到MaxUploadSizeExceededException异常时,自动跳到xxx面 -->
                <prop
                    key="org.springframework.web.multipart.MaxUploadSizeExceededException">error.jsp</prop>
            </props>
        </property>
    </bean>
    
</beans>
springMVV-servlet.xml
技术分享图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@  taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <center>
        <form action="<%=basePath%>importExcel" method="post"
            enctype="multipart/form-data">
                 上传文件:<input  type="file" name="uploadfile"> 
              <input type="submit"  value="上传">
        </form>
    </center>
</body>
</html>
index.jsp
技术分享图片
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.3.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-1.8.3.js"></script> -->
<script type="text/javascript">
$(function(){
    var msg="${msg}";
    if(msg!=null&&msg!=""){
        alert(msg);
    } 
})
</script>
<title>页面</title>
</head>
<body>
<h2>您好:${customer.name}!</h2><br>
<h1><font color="red"><a href="/MyDemo/02?name=${customer.name}">Quartz</a></font>---此刷新按钮每分钟最多刷新两次!!!</h1>
<br/><br/>
<h1>JasperReport</h1><br>
<a href="/MyDemo/03">下载</a>
<h1>pdfbox</h1><br>
<a href="/MyDemo/04">下载</a>|<a href="/MyDemo/05">上传</a>
</body>
</html>
01.jsp
技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <context-param>  
        <param-name>logbackConfigLocation</param-name>  
        <param-value>classpath:logback.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>  
    </listener>  
    <servlet>
        <servlet-name>servletdispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVV-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>servletdispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
web.xml
技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <context-param>  
        <param-name>logbackConfigLocation</param-name>  
        <param-value>classpath:logback.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>  
    </listener>  
    <servlet>
        <servlet-name>servletdispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVV-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>servletdispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
pom.xml
技术分享图片
/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50520
Source Host           : localhost:3306
Source Database       : orcl

Target Server Type    : MYSQL
Target Server Version : 50520
File Encoding         : 65001

Date: 2018-03-11 11:58:15
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `name` varchar(10) DEFAULT NULL,
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `pwd` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (‘name‘, ‘1‘, ‘123‘);
INSERT INTO `user` VALUES (‘min‘, ‘2‘, ‘ad‘);
INSERT INTO `user` VALUES (‘uanem‘, ‘3‘, ‘123‘);
INSERT INTO `user` VALUES (‘uanem‘, ‘16‘, ‘123‘);
INSERT INTO `user` VALUES (‘name‘, ‘44‘, ‘123‘);
INSERT INTO `user` VALUES (‘min‘, ‘45‘, ‘123‘);
INSERT INTO `user` VALUES (‘uanem‘, ‘46‘, ‘123‘);
INSERT INTO `user` VALUES (‘uanem‘, ‘47‘, ‘123‘);
user.sql

 

java框架-Springmvc-quzrtz-jasperreport-pio-pdfbox-jedis

标签:desc   output   _id   sem   scheduler   mys   别人   window   tput   

原文地址:https://www.cnblogs.com/ou-pc/p/8543667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!