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

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