如何从id获取QR码?

时间:2016-01-05 09:44:12

标签: spring qr-code thymeleaf

在我的控制器中,我有以下方法:

import net.glxn.qrgen.QRCode;
import org.marcio.demospringboot.dao.FormationRepository;
import org.marcio.demospringboot.model.Formation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayOutputStream;
import java.util.Map;

@Controller
public class FormationController {

@Autowired
private FormationRepository formationRepository;

@RequestMapping (value="formation/qr/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> qr(@PathVariable final Long id) {

    ByteArrayOutputStream stream = QRCode.from(formationRepository.findOne(id).toString()).stream();

    byte[] bytes = stream.toByteArray();

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED);
}
}

在我的html页面中:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>QR Code</title>
</head>
<body>

   <img th:src="@{/formation/qr/${id}}" />

</body>
</html>

这是生成的图片:

enter image description here

我想从您的&#34; id&#34;中获取用户数据。我正在使用一个简单的存储库Spring formationRepository和库net.glxn.qrgen.QRCode。该应用程序可以工作,但不会生成带有关于&#34; id&#34;的用户数据的QR代码。感谢。

2 个答案:

答案 0 :(得分:1)

在形成之前忘记'/'@RequestMapping (value="/formation/qr/{id}", method = RequestMethod.GET)

编辑:

ByteArrayOutputStream stream = QRCode.from(formationRepository.findOne(id).toString()).stream();
byte[] data = stream.toByteArray();;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(data.length);

return new HttpEntity<byte[]>(data, headers);

这应该按顺序工作,以便浏览器能够理解它是一个图像并显示它

答案 1 :(得分:0)

感谢您的帮助和评论。他们都非常有帮助。我可以通过升级到:

解决问题
@RequestMapping (value="/formation/qr/{id}", method = RequestMethod.GET)
public HttpEntity<byte[]> qr(@PathVariable Long id) {
    byte[] bytes = QRCode.from(formationRepository.findOne(id).getTheme()
                   .toString()).withSize(120, 120).stream().toByteArray();
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);
    headers.setContentLength(bytes.length);
    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED); 
}

解决方案是byte []bytes = QRCode.from(formation Repository.findOne (id).getTheme()。所以我得到了注册内容(getTheme)并以二维码形式呈现。