@RequestBody的使用及二维码的生成
2020-02-16 21:26
447 查看
@RequestBody主要用来接收前端传给后端的json字符串中的数据(请求体中的数据),GET没有请求体,所有用@RequestBody接收数据时,需要使用POST方式提交。
这里写了一个小demo(生成二维码),通过@RequestBody接收前端传来的json格式的字符串。
前端主要代码:
<form > 请支付0.01元,你就能用手机扫码百度了! <input id="price" name="price" type="hidden" value="0.01"/> <input type="button" value="确定" onclick="zhifu()"> <!-- 如果type用submit,点击确定后会刷新页面 --> <div id="result"> <img src="http://192.168.17.212:8081/uploadfile/weixinzhifu.png" id="qrcode" width="200px" height="250px"/> </div> </form>
AJAX请求:
<script> function zhifu(){ var price=$("#price").val(); console.log(price); var data1={price:price}; $.ajax({ type:"post", url:"${pageContext.request.contextPath}/blogs/getwxPayCode", //data:{price:price}, //注释报400 price:"0.01" data: JSON.stringify(data1), //{price:"0.01"} 转成json格式 cache:false, dataType:'json', contentType : "application/json", //注释 报415 success:function(data){ var photoUrl=data.photoUrl; console.log(data); console.log(data.photoUrl); $("#qrcode").attr("src",photoUrl); $("#qrcode").attr("height","200px"); }, error:function(){ alert("异常"); } }); } </script>
后端代码:
/** * 给前台返回二维码 @RequestBody:接收前台传的json字符串,请求方式要为POST * * @param json * @return */ @RequestMapping("getwxPayCode") @ResponseBody public JSON getwxPayCode(@RequestBody JSONObject json) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("price", json.get("price")); String imgPath = configUtil.getImgPath(); String uploadPath = imgPath.substring(imgPath.indexOf(":") + 1); // D:/image/ String wxPayUrl = "https://www.baidu.com"; String filename = new Random().nextInt(99999999) + ".jpg"; //八位随机数文件名 QRCodeUtil.encode(wxPayUrl, uploadPath + "wxPay/" + filename); //获取电脑IP,用于获取图片,图片路径映射前面博客有讲 String ip = InetAddress.getLocalHost().getHostAddress(); String port = configUtil.getPort(); //http://192.168.17.212:8081/uploadfile/wxPay/40823272.jpg String photoUrl = "http://" + ip + ":" + port + "/uploadfile/wxPay/" + filename; jsonObject.put("photoUrl", photoUrl); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; }
生成二维码的工具类:
public class QRCodeUtil { private static final String CHARSET = "utf-8"; private static final String FORMAT_NAME = "JPG"; // 二维码尺寸 private static final int QRCODE_SIZE = 300; // LOGO宽度 private static final int WIDTH = 60; // LOGO高度 private static final int HEIGHT = 60; /** * 生成二维码的图片 * * @param content * @param imgPath * @param needCompress * @return * @throws Exception */ private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Hashtable hints = new Hashtable(); 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); } } // 如果不写或者为null则返回一个没有嵌入图片的纯净的二维码 if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 QRCodeUtil.insertImage(image, imgPath, needCompress); return image; } /** * 二维码中间插入图片 * * @param source * @param imgPath * @param needCompress * @throws Exception */ private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception { File file = new File(imgPath); if (!file.exists()) { System.err.println("" + imgPath + " 该文件不存在!"); return; } Image src = ImageIO.read(new File(imgPath)); int width = src.getWidth(null); int height = src.getHeight(null); if (needCompress) { // 压缩LOGO if (width > WIDTH) { width = WIDTH; } if (height > HEIGHT) { height = HEIGHT; } Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(image, 0, 0, null); // 绘制缩小后的图 g.dispose(); src = image; } // 插入LOGO Graphics2D graph = source.createGraphics(); int x = (QRCODE_SIZE - width) / 2; int y = (QRCODE_SIZE - height) / 2; graph.drawImage(src, x, y, width, height, null); Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); graph.setStroke(new BasicStroke(3f)); graph.draw(shape); graph.dispose(); } /** * 嵌入图片的二维码,imgPath为null时,不嵌入 * * @param content * @param imgPath * @param destPath * @param needCompress * @throws Exception */ public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); mkdirs(destPath); // String file = new Random().nextInt(99999999)+".jpg"; // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file)); ImageIO.write(image, FORMAT_NAME, new File(destPath)); } public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); return image; } public static void mkdirs(String destPath) { File file = new File(destPath); // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常) if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } public static void encode(String content, String imgPath, String destPath) throws Exception { QRCodeUtil.encode(content, imgPath, destPath, false); } /** * 内容,二维码路径,两个参数 * * @param content * @param destPath * @throws Exception */ public static void encode(String content, String destPath) throws Exception { // 生成二维码,true:表示将嵌入二维码的图片进行压缩,如果为“false”则表示不压缩。 QRCodeUtil.encode(content, null, destPath, false); } public static void encode(String content, String imgPath, OutputStream output, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); ImageIO.write(image, FORMAT_NAME, output); } public static void encode(String content, OutputStream output) throws Exception { QRCodeUtil.encode(content, null, output, false); } /** * 获取二维码里面的数据 * * @param file * @return * @throws Exception */ public static String decode(File file) throws Exception { BufferedImage image; image = ImageIO.read(file); if (image == null) { return null; } BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; Hashtable hints = new Hashtable(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET); result = new MultiFormatReader().decode(bitmap, hints); String resultStr = result.getText(); return resultStr; } public static String decode(String path) throws Exception { return QRCodeUtil.decode(new File(path)); } public static void main(String[] args) throws Exception { // 存放在二维码中的内容 JSONObject jsonObject = new JSONObject(); jsonObject.put("types", 4); jsonObject.put("proCode", "360000"); jsonObject.put("province", "江西省"); jsonObject.put("city", "南昌市"); jsonObject.put("cityCode", "360100"); jsonObject.put("siName", "九江十九中"); jsonObject.put("siNumber", "7910001"); jsonObject.put("repetitionClass", 1); String text = jsonObject.toJSONString(); System.out.println(text); System.out.println(text.length()); // 根据时间戳获取二维码名字 long system = System.currentTimeMillis(); // String destPath = "D:/qrCode/qrcode/" + system + ".jpg"; String destPath = "D:/qrCode/qrcode/test.jpg"; QRCodeUtil.encode(text, destPath); // 解析二维码 String str = QRCodeUtil.decode(destPath); // 打印出解析出的内容 System.out.println(str); } /** * 测试有嵌入图片的二维码,二维码放地址 * * @throws Exception */ @Test public void test1() throws Exception { // 要加上http://,不然会看成字符串 String juzhiyuan = "http://www.baidu.com"; // 要嵌入二维码的图片路径,如果不写或者为null则生成一个没有嵌入图片的纯净的二维码 String imgPath = "D:/qrCode/baidu.jpg"; //嵌入的图片 String destPath = "D:/qrCode/qrcode/baidu.jpg"; // 生成中间有图片的二维码 QRCodeUtil.encode(juzhiyuan, imgPath, destPath, true); // 解析二维码,true:对嵌入的图片进行压缩 String str = QRCodeUtil.decode(destPath); // 打印出解析出的内容 System.out.println(str); } /** * 生成包含内容的二维码 * * @throws Exception */ @Test public void test2() throws Exception { // 存放在二维码中的内容 JSONObject jsonObject = new JSONObject(); jsonObject.put("types", 4); jsonObject.put("proCode", "360000"); jsonObject.put("province", "江西省"); jsonObject.put("city", "南昌市"); jsonObject.put("cityCode", "360100"); jsonObject.put("siName", "九江十九中"); jsonObject.put("siNumber", "7910001"); jsonObject.put("repetitionClass", 1); String text = jsonObject.toJSONString(); System.out.println(text); System.out.println(text.length()); // 根据时间戳获取二维码名字 // long system = System.currentTimeMillis(); // String destPath = "D:/qrCode/qrcode/" + system + ".jpg"; String destPath = "D:/qrCode/qrcode/testlian.jpg"; QRCodeUtil.encode(text, destPath); // 解析二维码 String str = QRCodeUtil.decode(destPath); // 打印出解析出的内容 System.out.println(str); } @Test public void test3() throws Exception { String path = "C:/home/cloudfile/payImage/7585821.jpg"; String str = QRCodeUtil.decode(path); // 解析二维码 System.out.println(str); } }
示例:
点击确定后,如下图:
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 求会做UI设计的,我想做个精灵表加载到游戏
- UE4中如何使物体始终朝向摄像头?
- UE4笔记:利用Widget设计一个切换材质功能
- UE4中的AI行为树简单介绍
- UE4 ios打包详解(一)
- UE4 ios打包详解(二)
- UE4如何开启光线追踪Ray Tracing
- UE4 直升机项目文档
- 关于Quixel Megascans软件及素材导入
- NGUI
- Invalid bound statement (not found): com.uestc.managesystem.dao.TMsgMapper.xxxx
- WebForm使用HttpWebRequest 调用webservice返回json
- Liquid/Elements侧链RPC API开发中文手册
- xui:基于Win32SDK方式的软件UI封装库(库+头文件+范例+源代码)
- 【Game】GuessNumber1.2.0
- The Theory and Practice of Revenue Management第二章阅读笔记(opl语言)
- UEFI+GPT模式下的Windows系统中分区结构和默认分区大小及硬盘整数分区研究
- UITableView的刷新
- 手势触摸定位(UIPanGestureRecognizer)
- Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean