Generating dynamic resources based on URI or parameters

You can dynamically generate responses based on e.g. query parameters by creating your own RequestHandler and registering it with the session.

In this way, you can for instance create an image that draws a text, given as a parameter to the image. This has been done in the example below:

Java

  1. public class DynamicImageUI extends UI {
  2. public static final String IMAGE_URL = "myimage.png";
  3. private final RequestHandler requestHandler = new RequestHandler() {
  4. @Override
  5. public boolean handleRequest(VaadinSession session,
  6. VaadinRequest request, VaadinResponse response)
  7. throws IOException {
  8. if (("/" + IMAGE_URL).equals(request.getPathInfo())) {
  9. // Create an image, draw the "text" parameter to it and output
  10. // it to the browser.
  11. String text = request.getParameter("text");
  12. BufferedImage bi = new BufferedImage(100, 30,
  13. BufferedImage.TYPE_3BYTE_BGR);
  14. bi.getGraphics().drawChars(text.toCharArray(), 0,
  15. text.length(), 10, 20);
  16. response.setContentType("image/png");
  17. ImageIO.write(bi, "png", response.getOutputStream());
  18. return true;
  19. }
  20. // If the URL did not match our image URL, let the other request
  21. // handlers handle it
  22. return false;
  23. }
  24. };
  25. @Override
  26. public void init(VaadinRequest request) {
  27. Resource resource = new ExternalResource(IMAGE_URL + "?text=Hello!");
  28. getSession().addRequestHandler(requestHandler);
  29. // Add an image using the resource
  30. Image image = new Image("A dynamically generated image", resource);
  31. setContent(image);
  32. }
  33. @Override
  34. public void detach() {
  35. super.detach();
  36. // Clean up
  37. getSession().removeRequestHandler(requestHandler);
  38. }
  39. }