ThymeleafにQRコードを表示する方法
ThymeleafでQRコードを表示する方法には、以下の手順を踏むことができます。
QRコードを生成するために、JavaのライブラリやAPIを使ってQRコードを生成し、その結果をThymeleafテンプレートで表示します。
以下の方法を試してみてください。
1. QRコードを生成するライブラリを選定
Javaでは、以下のようなライブラリを使ってQRコードを生成できます:
github.com
2. QRコードを生成するコードを作成
以下は、ZXingライブラリを使ってQRコードを生成する例です。
例: QRコードを生成してBase64エンコードする
import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.QRCode; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Hashtable; import javax.imageio.ImageIO; import java.util.Base64; public class QRCodeGenerator { public static String generateQRCodeImage(String text) throws Exception { QRCodeWriter qrCodeWriter = new QRCodeWriter(); Hashtable<EncodeHintType, ErrorCorrectionLevel> hints = new Hashtable<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 200, 200, hints); BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", outputStream); byte[] imageBytes = outputStream.toByteArray(); return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes); } }
3. コントローラでQRコードを生成し、Thymeleafテンプレートに渡す
コントローラで生成したQRコードのBase64エンコードされた画像データをThymeleafテンプレートに渡します。
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class QRCodeController { @GetMapping("/qrcode") public String getQRCode(Model model) { try { String qrCodeData = QRCodeGenerator.generateQRCodeImage("https://example.com"); model.addAttribute("qrCodeImage", qrCodeData); } catch (Exception e) { e.printStackTrace(); } return "qrcode"; } }
4. ThymeleafテンプレートでQRコードを表示する
ThymeleafテンプレートでQRコード画像を表示します。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>QRコード</title> </head> <body> <h1>QRコード</h1> <img th:src="${qrCodeImage}" alt="QRコード" /> </body> </html>
この方法で、QRコードをThymeleafテンプレートに表示することができます。