You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GeneratingDynamicResourcesBasedOnURIOrParameters.asciidoc 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. ---
  2. title: Generating Dynamic Resources Based On URI Or Parameters
  3. order: 28
  4. layout: page
  5. ---
  6. [[generating-dynamic-resources-based-on-uri-or-parameters]]
  7. = Generating dynamic resources based on URI or parameters
  8. You can dynamically generate responses based on e.g. query parameters by
  9. creating your own `RequestHandler` and registering it with the session.
  10. In this way, you can for instance create an image that draws a text,
  11. given as a parameter to the image. This has been done in the example
  12. below:
  13. [source,java]
  14. ....
  15. public class DynamicImageUI extends UI {
  16. public static final String IMAGE_URL = "myimage.png";
  17. private final RequestHandler requestHandler = new RequestHandler() {
  18. @Override
  19. public boolean handleRequest(VaadinSession session,
  20. VaadinRequest request, VaadinResponse response)
  21. throws IOException {
  22. if (("/" + IMAGE_URL).equals(request.getPathInfo())) {
  23. // Create an image, draw the "text" parameter to it and output
  24. // it to the browser.
  25. String text = request.getParameter("text");
  26. BufferedImage bi = new BufferedImage(100, 30,
  27. BufferedImage.TYPE_3BYTE_BGR);
  28. bi.getGraphics().drawChars(text.toCharArray(), 0,
  29. text.length(), 10, 20);
  30. response.setContentType("image/png");
  31. ImageIO.write(bi, "png", response.getOutputStream());
  32. return true;
  33. }
  34. // If the URL did not match our image URL, let the other request
  35. // handlers handle it
  36. return false;
  37. }
  38. };
  39. @Override
  40. public void init(VaadinRequest request) {
  41. Resource resource = new ExternalResource(IMAGE_URL + "?text=Hello!");
  42. getSession().addRequestHandler(requestHandler);
  43. // Add an image using the resource
  44. Image image = new Image("A dynamically generated image", resource);
  45. setContent(image);
  46. }
  47. @Override
  48. public void detach() {
  49. super.detach();
  50. // Clean up
  51. getSession().removeRequestHandler(requestHandler);
  52. }
  53. }
  54. ....