1、将jsp界面生成二维码:
package com.goldgrid.qrcode.servlet;
import java.io.IOException;
import java.net.InetAddress;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.goldgrid.qrcode.qrcodeone.EncoderHandler;
import com.goldgrid.qrcode.utils.UUIDUtil;
/**
* Servlet implementation class QRServlet
*/
public class QRServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String areaCode=request.getParameter("areaCode");
String businessID=request.getParameter("businessID");
String http=request.getScheme();
String ip=request.getServerName();
int port=request.getServerPort();
String projectName=request.getContextPath();
//String localIP = InetAddress.getLocalHost().getHostAddress();
HttpSession session = request.getSession();
String UUID=(String)session.getAttribute("UUID");
//System.out.println("--------"+UUID);
String content = http+"://"+ip+":"+port+projectName+"/qrcode/signature.jsp?AreaCode="+areaCode+"&BusinessID="+businessID+"&keyID="+UUID;
//System.out.println("二维码地址: "+ content);
EncoderHandler encoder = new EncoderHandler();
encoder.encoderQRCoder(content, response);
}
}
2、将参数和签名图片保存数据库:
package com.goldgrid.qrcode.servlet;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Decoder;
import com.goldgrid.qrcode.dao.SignatureDao;
import com.goldgrid.qrcode.domain.PictureInfo;
import com.goldgrid.qrcode.service.PictureService;
import com.goldgrid.qrcode.service.PictureServiceImpl;
/**
* Servlet implementation class SignatureServlet
*/
public class SignatureServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@SuppressWarnings("resource")
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
PictureService pictureService=new PictureServiceImpl();
//PictureService pictureService;
//得到Bean注入的值
/*PictureService pictureService = (PictureService)SpringContext.getBean("pictureService");*/
//图片信息实体类
PictureInfo pictureInfo = new PictureInfo();
//签名图片保存目录
String basePath = this.getServletContext().getRealPath("/qianmingPicture/");
System.out.println("签名保存目录-----"+basePath);
//返回实例
PrintWriter out = resp.getWriter();
String commond = req.getParameter("commond");
if("qianMing".equals(commond)){
resp.setContentType("text/html;charset=utf-8");
String uuid = req.getParameter("keyID");
String areaCode = req.getParameter("areaCode");
String businessID = req.getParameter("businessID");
req.setAttribute("keyID", uuid);
req.setAttribute("areaCode", areaCode);
req.setAttribute("businessID", businessID);
req.getRequestDispatcher("/qrcode/signature.jsp").forward(req, resp);
//System.out.println("使用请求转发到签名界面!!!");
}else if("save".equals(commond)){
String uuid = req.getParameter("keyID");
String areaCode = req.getParameter("areaCode");
String businessID = req.getParameter("businessID");
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String signTimet=df.format(new Date());
java.util.Date ud = null;
try {
ud = df.parse(signTimet);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Timestamp signTime = new java.sql.Timestamp(ud.getTime());
String basePicture = req.getParameter("basePicture");
//得到签名base64流
//basePicture = basePicture.substring(22, basePicture.length());
//签名之后的图片名
//String fileName = GenerateImage(basePicture,basePath);
byte[] signPicByte=basePicture.getBytes();
if(signPicByte != null){
//查询该订单是否存在
PictureInfo picture = new PictureInfo();
try {
picture = pictureService.getPictureUUid(uuid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(picture == null){
pictureInfo.setUuid(uuid);
pictureInfo.setAreaCode(areaCode);
pictureInfo.setBusinessID(businessID);
pictureInfo.setSignTime(signTime);
//pictureInfo1.setSignPic(fileName);
boolean d = false;
boolean b = false;
try {
d = pictureService.toSavePicture(pictureInfo);
b = pictureService.putSignPic(uuid, signPicByte);
req.setAttribute("keyID", uuid);
//resp.sendRedirect("/iSolutions-BDEAH/qrcode.jsp");
//System.out.println("------走过重定向方法---------");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(d&&b){
System.out.println("保存图片信息成功");
out.write("1");
}
}else{
/*pictureInfo.setUuid(uuid);
pictureInfo.setAreaCode(areaCode);
pictureInfo.setBusinessID(businessID);
pictureInfo.setSignTime(signTime);
pictureInfo.setSignTime(signTime);
pictureInfo.setSignPic(fileName);*/
boolean i = false;
boolean up = false;
try {
i = pictureService.uploadPicture(areaCode, businessID,signTime,uuid);
up = pictureService.putSignPic(uuid, signPicByte);
//pictureService.uploadPicture( areaCode, businessID,signTime,"15");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i&&up){
System.out.println("更新图片信息成功");
out.write("2");
}
}
}
}else if("query".equals(commond)){
resp.setContentType("img/jpg");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String uuid = req.getParameter("keyID");
pictureInfo.setUuid(uuid);
try {
pictureInfo = pictureService.getPictureUUid(uuid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(pictureInfo != null){
Blob fileName = pictureInfo.getSignPic();
String fileUrl = basePath + "/" + fileName;
FileInputStream fis = new FileInputStream(fileUrl);
byte[] buff = new byte[1024];
int len = 0;
//图片转二进制
while ((len = fis.read(buff)) != -1){
bos.write(buff, 0, len);
}
byte[] result = bos.toByteArray();
//得到图片的16字节数组
String str = byte2HexStr(result);
out.write(str);
}else{
out.write("");
}
}
}
/**
* base64转图片
* @ClassName:ZS
* @date 2017年11月10日
* @param imgStr
* @param basePath
* @return
*/
public static String GenerateImage(String imgStr,String basePath){
if (imgStr == null)
return "";
BASE64Decoder decoder = new BASE64Decoder();
try{
byte[] b = decoder.decodeBuffer(imgStr);
for(int i = 0;i < b.length;++i){
if(b[i]<0){
b[i] += 256;
}
}
UUID uuid = UUID.randomUUID();
if (!new File(basePath).exists()) {
new File(basePath).mkdirs();
}
String fileName = uuid + ".png";
String imgFilePath = basePath + "/" + fileName;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();out.close();
String jpgName = pngTojpg(imgFilePath,basePath);
return jpgName;
}catch (Exception e){
return "";
}
}
/**
* 二进制转16进制
* @ClassName:ZS
* @date 2017年11月10日
* @param b
* @return
*/
public static String byte2HexStr(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++){
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
/**
* png转jpg
* @ClassName:ZS
* @date 2017年11月13日
* @param fileName
* @return
*/
public static String pngTojpg(String fileName,String basePath){
String jpgName = UUID.randomUUID().toString() + ".jpg";
String jpgFilePath = basePath + "/" + jpgName;
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(new File(fileName));
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
//TYPE_INT_RGB:创建一个RBG图像,24位深度,成功将32位图转化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
ImageIO.write(newBufferedImage, "jpg", new File(jpgFilePath));
} catch (IOException e) {
e.printStackTrace();
}
if (new File(fileName).exists()) {
new File(fileName).delete();
}
return jpgName;
}
}
3、PictureServiceImpl
package com.goldgrid.qrcode.service;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import com.goldgrid.mobile.model.OrderLog;
import com.goldgrid.qrcode.dao.SignatureDao;
import com.goldgrid.qrcode.domain.PictureInfo;
import com.goldgrid.uploadImg.bean.UploadImg;
public class PictureServiceImpl implements PictureService {
private SignatureDao signatureDao1;
SignatureDao signatureDao=new SignatureDao();
@Override
public boolean toSavePicture(PictureInfo pictureInfo)throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.savePictureInfo(pictureInfo);
}
@Override
public PictureInfo queryPicture(String uuid) {
// TODO Auto-generated method stub
return this.signatureDao.queryPictureInfo(uuid);
}
@Override
public PictureInfo getPictureUUid(String uuid) throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.getPictureUUid(uuid);
}
@Override
public boolean uploadPicture(String areaCode,String businessID,Timestamp signTime,String uuid) throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.uploadPicture(areaCode,businessID,signTime,uuid);
}
@Override
public boolean putSignPic(String uuid, byte[] signPic) throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.putSignPic(uuid, signPic);
}
@SuppressWarnings("unchecked")
@Override
public List<PictureInfo> getImage(Integer picToPdf) throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.getImage(picToPdf);
}
@Override
public List<UploadImg> queryPicturePath(String areaCode, String businessID) throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.queryPicturePath(areaCode,businessID);
}
@Override
public List<OrderLog> queryPDFPath(String areaCode, String businessID)
throws SQLException {
// TODO Auto-generated method stub
return this.signatureDao.queryPDFPath(areaCode,businessID);
}
}
4、SignatureDao
package com.goldgrid.qrcode.dao;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import oracle.sql.BLOB;
import com.goldgrid.mobile.model.OrderLog;
import com.goldgrid.mobile.orderLogNew.OrderLogNew;
import com.goldgrid.mobile.orderLogNew.OrderLogNewDao;
import com.goldgrid.mobile.renxiang.domain.RenxiangConfig;
import com.goldgrid.mobile.util.JdbcTemplate;
import com.goldgrid.mobile.util.jdbc.CallBack;
import com.goldgrid.mobile.util.jdbc.DataSourceUtils;
import com.goldgrid.qrcode.domain.PictureInfo;
import com.goldgrid.uploadImg.bean.UploadImg;
import com.goldgrid.web.util.SignExcuteUtil;
import com.mchange.v2.c3p0.impl.NewProxyResultSet;
public class SignatureDao extends JdbcTemplate {
private static Logger logger = LogManager.getLogger(SignatureDao.class);
private static final SignatureDao INSTANCE = new SignatureDao();
public SignatureDao(){}
public static SignatureDao getInstance(){
return INSTANCE;
}
public boolean savePictureInfo(PictureInfo pictureInfo) throws SQLException {
String sql = "insert into t_signature(areaCode,businessID,uuid,signTime,signPic) " +
"values(?,?,?,?,empty_blob())";
return update(sql, new Object[]{pictureInfo.getAreaCode(),pictureInfo.getBusinessID()
,pictureInfo.getUuid(),pictureInfo.getSignTime()}) > 0;
}
public PictureInfo queryPictureInfo(String uuid) {
// TODO Auto-generated method stub
return null;
}
public PictureInfo getPictureUUid(String uuid)throws SQLException {
String sql = "select * from t_signature where uuid=?";
PictureInfo pictureInfos = (PictureInfo)queryForObject(sql, new Object[]{uuid}, new CallBack(){
public Object doInPreparedStatement(ResultSet rs)
throws SQLException {
PictureInfo pictureInfo = new PictureInfo();
pictureInfo.setTid(rs.getInt("tid"));
pictureInfo.setUuid(rs.getString("uuid"));
pictureInfo.setAreaCode(rs.getString("areaCode"));
pictureInfo.setBusinessID(rs.getString("businessID"));
pictureInfo.setSignTime(rs.getDate("signTime"));
//pictureInfo.setSignPic(rs.getString("signPic"));
//2015-12-14
if(null != rs){
rs.close();
}
return pictureInfo;
}
});
return pictureInfos;
}
public boolean uploadPicture(String areaCode,String businessID,Timestamp signTime,String uuid) throws SQLException {
String sql = "update t_signature set areaCode=?,businessID=?,signTime=? where uuid=?";
return update(sql, new Object[]{areaCode
,businessID,signTime,uuid})>0;
}
/*public boolean updateSignature(String uuid,String areaCode,String business,java.sql.Timestamp signTime)
throws SQLException{
String sql = "update t_signature set uuid=?,areaCode=?,businessID=?,signTime=? where uuid=?";
return update(sql, new Object[]{uuid,areaCode,business,areaCode});
} */
public boolean putSignPic(String uuid, byte[] signPic) throws SQLException{
boolean b = false;
Statement stmt = null;
NewProxyResultSet update = null;
Connection conn = DataSourceUtils.getConnection();
if (conn != null) {
try {
stmt = conn.createStatement();
stmt.executeUpdate("UPDATE T_SIGNATURE SET SIGNPIC=EMPTY_BLOB() WHERE UUID='" + uuid + "'");
stmt.close();
conn.setAutoCommit(false);
stmt = conn.createStatement();
update = (NewProxyResultSet) stmt
.executeQuery("SELECT SIGNPIC FROM T_SIGNATURE WHERE UUID='" + uuid + "'FOR UPDATE");
if (update != null && update.next()) {
BLOB strSignData = null;
strSignData = (BLOB) update.getBlob("SIGNPIC");
byte[] temp_byte_xml = signPic;
if (temp_byte_xml != null) {
b = PutAtBlob(strSignData, signPic,
temp_byte_xml.length);
conn.commit();
conn.setAutoCommit(true);
}
}
} catch (Exception e) {
logger.error(e);
return false;
} finally {
try {
if (update != null) {
update.close();
}
} catch (SQLException e) {
logger.error("OracleResultSet关闭异常:" + e.toString());
}
try {
//2015-12-14
if(stmt != null){
stmt.close();
}
} catch (SQLException e) {
logger.error("Statement关闭异常:" + e.toString());
}
try {
//2015-12-14
if(conn != null){
conn.close();
}
} catch (SQLException e) {
logger.error("数据库连接关闭异常:" + e.toString());
}
}
}
return b;
}
/**
* 从字节数组中存放规定大小的数据至ORCLE BLOB对象中
*
* @param vField
* ORCLE BLOB对象
* @param b
* 字节数组
* @param vSize
* 存放的大小
* @return true 存放成功;false 存放失败
* @throws SQLException
* @throws IOException
*/
private boolean PutAtBlob(BLOB vField, byte[] b, int vSize)
throws SQLException, IOException {
boolean mResult = false;
OutputStream outstream = null;
try {
outstream = vField.getBinaryOutputStream();
outstream.write(b, 0, vSize);
// outstream.write(b);
outstream.close();
mResult = true;
} catch (IOException e) {
logger.error(e.toString());
} finally {
if (outstream != null) {
SignExcuteUtil.outputStreamClose(outstream);
}
}
return mResult;
}
@SuppressWarnings("unchecked")
public List<PictureInfo> getImage(Integer pictoPdf)throws SQLException {
String sql = "select * from t_signature where pictopdf=?";
List<PictureInfo> pictureInfos = (List<PictureInfo>)queryForObject(sql, new Object[]{pictoPdf}, new CallBack(){
public Object doInPreparedStatement(ResultSet rs)
throws SQLException {
List<PictureInfo> list=new ArrayList<PictureInfo>();
while(rs.next()){
PictureInfo pictureInfo = new PictureInfo();
pictureInfo.setTid(rs.getInt("tid"));
pictureInfo.setUuid(rs.getString("uuid"));
pictureInfo.setAreaCode(rs.getString("areaCode"));
pictureInfo.setBusinessID(rs.getString("businessID"));
pictureInfo.setSignTime(rs.getDate("signTime"));
pictureInfo.setSignPic(rs.getBlob("signPic"));
list.add(pictureInfo);
}
if(null != rs){
rs.close();
}
return list;
}
});
return pictureInfos;
}
@SuppressWarnings("unchecked")
public List<UploadImg> queryPicturePath(String areaCode,String businessID)throws SQLException {
String sql = "SELECT * FROM T_UPLOADIMG WHERE AREACODE=? AND BUSINESSID=?";
Object[] args = new Object[] {areaCode,businessID};
List<UploadImg> uploadImgList = (List<UploadImg>) super.query(sql, args, new CallBack() {
public Object doInPreparedStatement(ResultSet rs) throws SQLException {
List<UploadImg> list= new ArrayList<UploadImg>();
while(rs.next()){
UploadImg uploadImg = new UploadImg();
uploadImg.setTid(rs.getInt("tid"));
uploadImg.setAuthCode(rs.getString("authCode"));
uploadImg.setPhotoPath(rs.getString("photopath"));
uploadImg.setOptCode(rs.getString("optCode"));
uploadImg.setPhotoSharePath( rs.getString("photoSharePath"));
uploadImg.setHeight(rs.getFloat("height"));
uploadImg.setWidth(rs.getFloat("width"));
uploadImg.setFileStorType(rs.getString("fileStorType"));
uploadImg.setExt1(rs.getString("ext1"));
uploadImg.setExt2(rs.getString("ext2"));
uploadImg.setExt3(rs.getString("ext3"));
uploadImg.setExt4(rs.getString("ext4"));
uploadImg.setExt5(rs.getString("ext5"));
list.add(uploadImg);
}
if(rs != null){
rs.close();
}
return list;
}
});
return uploadImgList;
}
@SuppressWarnings("unchecked")
public List<OrderLog> queryPDFPath(String areaCode, String businessID) throws SQLException {
// TODO Auto-generated method stub
String sql = "SELECT * FROM T_ORDER_LOG WHERE AREACODE=? AND BUSINESSID=?";
Object[] args = new Object[] {areaCode,businessID};
List<OrderLog> orderLogs = (List<OrderLog>) super.query(sql, args, new CallBack() {
public Object doInPreparedStatement(ResultSet rs) throws SQLException {
List<OrderLog> list= new ArrayList<OrderLog>();
while(rs.next()){
OrderLog orderLog = new OrderLog();
orderLog.setTid(rs.getInt("tid"));
orderLog.setAreaCode(rs.getString("areacode"));
orderLog.setAreaName(rs.getString("areaname"));
orderLog.setAuthType(rs.getString("authtype"));
orderLog.setBusinessId(rs.getString("businessid"));
orderLog.setBusinessType(rs
.getString("businesstype"));
orderLog.setOperateCode(rs.getString("operatecode"));
orderLog.setOperateName(rs.getString("operatename"));
orderLog.setMobile(rs.getString("mobile"));
orderLog.setCustomerName(rs
.getString("customername"));
orderLog.setIdCard(rs.getString("idcard"));
orderLog.setUnionPrint(rs.getString("unionprint"));
orderLog.setSignType(rs.getString("signtype"));
orderLog.setUnionCount(rs.getInt("unioncount"));
orderLog.setBusinessDate(rs
.getString("businessdate"));
orderLog.setBusinessFileName(rs
.getString("businessfilename"));
orderLog.setAccFileName(rs
.getString("accfilename"));
orderLog.setBusinessFileUrl(rs
.getString("businessfileurl"));
orderLog.setAccFileUrl(rs.getString("accfileurl"));
orderLog.setBusinessFileSize(rs
.getInt("businessfilesize"));
orderLog.setAccFileSize(rs.getInt("accfilesize"));
orderLog.setBusinessFileHash(rs
.getString("businessfilehash"));
orderLog.setAccFileHash(rs
.getString("accfilehash"));
orderLog.setMacId(rs.getString("macid"));
orderLog.setLogIp(rs.getString("logip"));
orderLog.setLogDate(rs.getString("logdate"));
orderLog.setExt1(rs.getString("ext1"));
orderLog.setExt2(rs.getString("ext2"));
orderLog.setExt3(rs.getString("ext3"));
orderLog.setExt4(rs.getString("ext4"));
orderLog.setExt5(rs.getString("ext5"));
orderLog.setExt6(rs.getString("ext6"));
orderLog.setSucessSign(rs.getString("sucesssign"));
orderLog.setSucessPost1(rs
.getString("sucesspost1"));
orderLog.setSucessPost2(rs
.getString("sucesspost2"));
orderLog.setSucessPost3(rs
.getString("sucesspost3"));
orderLog.setPostCount(rs.getInt("postcount"));
orderLog.setUrl1(rs.getString("url1"));
orderLog.setUrl2(rs.getString("url2"));
orderLog.setUrl3(rs.getString("url3"));
orderLog.setLogMemo(rs.getString("logmemo"));
orderLog.setImageSystemID(rs
.getString("imagesystemid"));
orderLog.setBusinessFilePath(rs
.getString("businessfilepath"));
orderLog.setAccFilePath(rs
.getString("accfilepath"));
orderLog.setAddFilePath(rs
.getString("addfilepath"));
orderLog.setAddFileUrl(rs.getString("addfileurl"));
orderLog.setMakeFileType(rs
.getString("makefiletype"));
orderLog.setModifyTimes(rs
.getString("modifytimes"));
orderLog.setToDocIndex(rs.getString("todocindex"));
orderLog.setIsYiyifu(rs.getString("isyiyifu"));
orderLog.setBusinessHall(rs
.getString("businesshall"));
orderLog.setBusinessHallId(rs
.getString("businesshallid"));
orderLog.setCrmxmlSize(rs.getString("crmxmlsize"));
orderLog.setFileStorType(rs.getString("FileStorType"));
orderLog.setBFSharePath(rs.getString("bFSharePath"));
orderLog.setAFSharePath(rs.getString("aFSharePath"));
orderLog.setFileShareFlag(rs.getString("FileShareFlag"));
orderLog.setImportPdfSize(rs.getString("importPdfSieze"));
orderLog.setHzdCheckCode(rs.getString("hzdCheckCode"));
orderLog.setAssociatedIDs(rs.getString("associatedIDs"));
orderLog.setCardType(rs.getString("cardType"));
list.add(orderLog);
}
if(rs != null){
rs.close();
}
return list;
}
});
return orderLogs;
}
}