记录一下做的二维码签到功能 maven项目
1.首先引入二维码jar包 ,可去中央仓库下载
<!-- 生成二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/webapp/WEB-INF/lib/core-3.1.0.jar</systemPath>
</dependency>
这种依赖方式可以将jar包放在 项目lib目录下 ,如果下载到本地仓库里,version后面俩标签可不用配置,这里记下这种方式。
2.写一个生成二维码工具类 ,不带图片的
package com.yihaomen.barcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.Hashtable;
import java.util.UUID;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class Qr {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
private static BufferedImage createImage(String content) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
return image;
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath
* 存放目录
* @throws Exception
*/
public static String encode(Long offlineTrainingId) throws Exception {
//根据当前日期创建父级目录
String mkdir = DateUtil.formatDateToZHStyle(new Date())+"/";
//此处需要更换文件保存地址 "d:/wdcloud/uploaddata/qrcode/"
String destPath = "d:/wdcloud/uploaddata/qrcode/"+mkdir;
//此处需要更换服务器域名 "http://zhd-demos.wdcloud.dev/"
String content = "http://zhd-demos.wdcloud.dev/vocation-web/offlineTraining/getQrCode/"+offlineTrainingId;
BufferedImage image = Qr.createImage(content);
mkdirs(destPath);
String file = UUID.randomUUID().toString().replace("-", "")+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+file));
//此处需要更换图片展示域名 "http://zhd-demos.wdcloud.dev/"
String qrcodeUrl = "http://zhd-demos.wdcloud.dev/pic/"+mkdir+file;
return qrcodeUrl;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public static void main(String[] args) throws Exception {
Long text = 1L;
Qr.encode(text);
}
}
这里将图片保存在本地,开发中,本地路径应该换成服务器图片理解,二维码图片展示路径也换成nginx域名路径。
String content = "http://zhd-demos.wdcloud.dev/vocation-web/offlineTraining/getQrCode/"+offlineTrainingId; 这是二维码图片存的信息,用户扫描二维码,调到这个controller
下的接口里
@Controller
@RequestMapping("/trainingUser")
public class TrainingUserController {
/**
* 扫描二维码接口
*
* @author 张浩东
* @param offlineTrainingId 培训任务id
* @return
*/
@RequestMapping("/getQrCode/{offlineTrainingId}") //可以在路径里携带参数,路径变量
public String getQrCode(@PathVariable("offlineTrainingId") Long offlineTrainingId,HttpServletRequest request){
try {
Map<String, Object> result = offlineTrainingService.getOfflineTrainingInfo(offlineTrainingId);
return "redirect:/jsp/qiandao.html?offlineTrainingId="+offlineTrainingId+"&startTime="+result.get("startTime")+"&endTime="+result.get("endTime");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
service层就是调用dao接口,像表里拿一些数据,给静态页面用,注意:后台给html传值,可以通过拼接参数的方式,必须要使用重定向,因为重定向之后,地址栏就变成我拼接的路径,这样可以在js里获得url里的参数
html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>Insert title here</title>
<script type="text/javascript" src="../ui/common/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
var request = { //这两种方法都可以获得url里面的参数
QueryString : function(val) {
var uri = window.location.search; //获得url里 ? 之后的路径
var re = new RegExp("" + val + "\=([^\&\?]*)", "ig");
return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1))
: null);
},
QueryStrings : function() {
var uri = window.location.search;
var re = /\w*\=([^\&\?]*)/ig;
var retval = [];
while ((arr = re.exec(uri)) != null)
retval.push(arr[0]);
return retval;
}
}
var data = request.QueryStrings();
var offTrainId = data[0].split("=");
var startTime = data[1].split("=");
var endTime = data[2].split("=");
window.onload = function() {
$("#offTrainId").val(offTrainId[1])
$("#span1").html(startTime[1].replace(/%20/," "));
$("#span2").html(endTime[1].replace(/%20/," "));
}
</script>
</head>
<body>
<h2>签到</h2>
开始时间:
<span style="color: green;" id="span1"></span>
<br />
结束时间:
<span style="color: green;" id="span2"></span>
<br />
<form action="../trainingUser/qrCodeSign" method="GET">
<input type="hidden" name="offTrainId" id="offTrainId" />
<input type="text" name="mobileNumStr" /><br />
<input type="submit" value="签到" /><br />
</form>
</body>
</html>
点击签到后,进入签到controller里的接口
@Controller
@RequestMapping("/trainingUser")
public class TrainingUserController {
/**
* 二维码扫描签到
* @author zhanghaodong
* @param offTrainId 培训任务id mobileNumStr 手机号
* @return
*/
@RequestMapping(value = "/qrCodeSign", method = RequestMethod.GET)
@ResponseBody
public Object qrCodeSign(Long offTrainId,String mobileNumStr){
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
if (offTrainId != null && mobileNumStr != null && mobileNumStr.trim() !="") {
Long mobileNum = Long.valueOf(mobileNumStr);
Integer result = trainingUserService.selectByMobileNum(offTrainId, mobileNum);
if (result == 1) {
trainingUserService.updateTrainingUserByMobileNum(offTrainId, mobileNum);
resultMap.put(VocationConstants.KEY_RESULT_ISSUCCESS, VocationConstants.STRING_TRUE);
resultMap.put(VocationConstants.KEY_RESULT_MSGCODE, VocationConstants.ERROR_CODE_CZCG);
} else {
resultMap.put(VocationConstants.KEY_RESULT_ISSUCCESS, VocationConstants.STRING_FALSE);
resultMap.put(VocationConstants.KEY_RESULT_MSGCODE, "0013");// 查询不到此人信息,无法签到
}
} else {
resultMap.put(VocationConstants.KEY_RESULT_ISSUCCESS, VocationConstants.STRING_FALSE);
resultMap.put(VocationConstants.KEY_RESULT_MSGCODE, "0014");// 页面异常
}
} catch (Exception e) {
resultMap.put(VocationConstants.KEY_RESULT_ISSUCCESS, VocationConstants.STRING_FALSE);
resultMap.put(VocationConstants.KEY_RESULT_MSGCODE, "0012");// 签到失败
}
return resultMap;
}
}
get post请求 都可以 但是微信对于不知名url 会拦截 post会有点问题, 别的手机浏览器没问题。所以用了get
二维码生成项目
http://files.cnblogs.com/files/zhd-axx/barcodesample.rar